Last active
November 11, 2022 07:00
-
-
Save deepakxyz/cab38fcbc73e534a81db42b991b257ac to your computer and use it in GitHub Desktop.
Walk through nested dic and return with parent
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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