Sunday, 15 September 2013

Python--Finding Parent Keys for a specific value in a nested dictionary

Python--Finding Parent Keys for a specific value in a nested dictionary

I am struggling to process a nested dictionary, and return the nested
Parent Keys, for a specific Value, when the Value may exist more than once
in the nested dictionary. For example:
example_dict = { 'key1' : 'value1', 'key2' : 'value2', 'key3' : { 'key3a':
'value3a' }, 'key4' : { 'key4a': { 'key4aa': 'value4aa', 'key4ab':
'value4ab', 'key4ac': 'value1'}, 'key4b': 'value4b'} }
You will notice that 'value1' appears twice in the above dictionary, and I
would like to create a function that returns either a single list, or a
series of lists, that identify the different Parent Keys, which in this
case would be 'key1' and ('key4', 'key4a', key4ac).
This type of problem was dealt with elsewhere on this site, when the Value
one was looking for only appeared once, and was readily handled by the
following recursive function:
def find_key(d,key): for k,v in d.items(): if isinstance(v,dict): p =
find_key(v,key) if p: return [k] + p elif v == key: return [k]
print find_key(example_dict,'value4ac').
If you run the above code on the dictionary, I only get one answer for the
parent keys. Any help would be much appreciated, Thanks!

No comments:

Post a Comment