I've searched over stackoverflow and found the following code that allow me to search for a key values in nested dict recursively. However, I also want to keep track of the outer dict's key value. How should I do that?
from Alfe's answer in the below link, I can use the code below get all the values of the key in nested dict. Find all occurrences of a key in nested python dictionaries and lists
data = {'item1': {
'name': 'dummy',
'type': 'dummy1'},
'item2': {
'name': 'dummy',
'type': 'dummy1',
'label':'label2'
},
'item3': {
'name': 'dummy',
'type': 'dummy1',
'label':'label3'},
'item4': {
'name': 'dummy',
'type': 'dummy1'}
}
def find(key, dictionary):
for k, v in dictionary.items():
if k == key:
yield v
elif isinstance(v, dict):
for result in find(key, v):
yield result
elif isinstance(v, list):
for d in v:
for result in find(key, d):
yield result
In[1]:list(find('label', data))
Out[1]:
['label2', 'label3']
However, I also need to keep record of the outer dict key as below. How should I do this? Also my data can potentially have more than one layer.
{'item2':'label2',
'item3':'label3'
}
I also find the recursive_lookup in this link very neatly written. However, it's returning None
when I tried to run it.
Find keys in nested dictionary
def recursive_lookup(k, d):
if k in d:
return d[k]
for v in d.values():
if isinstance(v, dict):
return recursive_lookup(k, v)
return None
It's returning None
when I call recursive_lookup('label', data)
.
If anyone can point out for me why the above code is not working that would be great too!