Reputation: 21
I have a dictionary that looks like this:
d = {'dev':
{<dev1>:
{'mod':
{<mod1>:
{'port': [1, 2, 3]
}
}
}
<dev2>:
{'mod':
{<mod3>:
{'port': [] }
}
}
}
}
I want to be able to write a function, such that if i provide a search object such as 'mod1', it provides me the parent key as 'dev1'.
I have searched all over and tried a bunch of things, but couldnt seem to get this to work. Any help will be appreciated!
I have tried the stuff mentioned at the link below:
Python--Finding Parent Keys for a specific value in a nested dictionary
Find a key in a python dictionary and return its parents
Upvotes: 0
Views: 4260
Reputation: 229361
This should work:
def find_parent_keys(d, target_key, parent_key=None):
for k, v in d.items():
if k == target_key:
yield parent_key
if isinstance(v, dict):
for res in find_parent_keys(v, target_key, k):
yield res
Usage:
d = {
'dev': {
'dev1': {
'mod': {
'mod1': {'port': [1, 2, 3]},
},
},
'dev2': {
'mod': {
'mod3': {'port': []},
},
},
},
}
print list(find_parent_keys(d, 'mod'))
print list(find_parent_keys(d, 'dev'))
Output:
['dev2', 'dev1']
[None]
Upvotes: 1