Reputation: 3895
I want to search for key-value pairs in Python dict. My dict is nested, so simple solution like:
if 'keyname' in my_dict:
...
or:
for key, value in my_dict.items():
if 'keyname' == key:
does not work for me. This is my dict:
my_dict = {'a': 111,
'b': 222,
'c':{'d': 333,
'e': 444},
'f':555,
'g':{'h': {'i': 666}}}
And I want to find value of 'i' or 'd', whats the simplest way to do that? I do not care for name of the key that has nested dict. For example, I do not care for key name of 'c' or 'g' or 'h', I only care about key-values (key-number). Is there a way to transform my dict to look like this:
my_result = {'a': 111,
'b': 222,
'd': 333,
'e': 444,
'f': 555,
'i': 666}
In that way it would be easy.
Upvotes: 2
Views: 165
Reputation: 3537
try this one:
def find_value(_key, _dict):
for key, value in list(_dict.items()):
if isinstance(value, dict):
result = find_value(_key, value)
if result:
return result
if key == _key:
return value
Upvotes: 0
Reputation: 20689
You can flatten the dictionary using recursion here.
def flat(data):
out = {}
for k, v in data.items():
if isinstance(v, dict):
out.update(flat(v))
else:
out[k] = v
return out
flat(my_dict)
# {'a': 111, 'b': 222, 'd': 333, 'e': 444, 'f': 555, 'i': 666}
Upvotes: 2