Skip to content

Instantly share code, notes, and snippets.

@deepakxyz
Last active November 11, 2022 07:00
Show Gist options
  • Save deepakxyz/cab38fcbc73e534a81db42b991b257ac to your computer and use it in GitHub Desktop.
Save deepakxyz/cab38fcbc73e534a81db42b991b257ac to your computer and use it in GitHub Desktop.
Walk through nested dic and return with parent
dic = {
"root_grp": {
"a":{
"a1":{
"aa1":{},
"aa2":{}
},
"a2":{}
} ,
"b":{
"b1":{},
"b2":{
"c":{
"c1":{} ,
"c2":{}
},
"d":{
"d1":{},
"d2":{}
}
}
}
}
}
class walk():
I = 0
PARENT_LIST = []
PARENT = None
@classmethod
def run(cls, dic, parent=None):
for key , item in dic.items():
print(walk.PARENT, key)
if len(item.keys()) > 0:
parent = key
walk.PARENT_LIST.append(parent)
walk.PARENT = parent
cls.run(item, parent=parent)
else:
try:
walk.PARENT = walk.PARENT_LIST[-1]
del walk.PARENT_LIST[-1]
except:
pass
walk.run(dic)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment