Reputation: 107
Seems to be many questions like this but I can't find this specific answer. Let's say I have a dictionary like so:
{"keyA":
{"a": "blue", "b": {"b1": "sky", "b2": "baby", "b3": "navy"},
"keyB":
{"x": "horse", "y": {"y1": "stallion", "y2": "thoroughbred"}, "z": {"z1": "white", "z2": "black"}}
"keyC": "father"
}
Is there any easy way to get the value of 'z1' (or any nested key) if I DO NOT KNOW it's parent key or the location of the parent key within the dictionary?
I was thinking a recursive function where I pass 'z1' as the key I'm searching for and it runs through the dictionary until there is a match, but I haven't been able to get that to work.
Upvotes: 0
Views: 2098
Reputation: 2090
Making a recursive function is a good guess:
data = {'keyA':
{'a': 'blue', 'b': {'b1': 'sky', 'b2': 'baby', 'b3': 'navy'},
'keyB':
{'x': 'horse', 'y': {'y1': 'stallion', 'y2': 'thoroughbred'}, 'z': {'z1': 'white', 'z2': 'black'}},
'keyC': 'father'
}}
def find_value(data, key):
if not isinstance(data, dict):
return None
try:
return data[key]
except KeyError:
for sub_data in data.values():
sub_value = find_value(sub_data, key)
if sub_value is not None:
return sub_value
return None
print(find_value(data, 'z1'))
# 'white'
print(find_value(data, 'z4'))
# None
Upvotes: 3