I have a nested dictionary that contains dictionaries of key value pairs pulled from json. For instance a nested dictionary called 'some_dict':
{1: {'address': 'some address', 'status': 'some status', 'name': 'some name'},
2: {'address': 'some other address', 'status': 'some other status', 'name': 'some other name'}}
I need to search this nested dictionary for a specific value of key 'status', and when it matches, return all the values of that dictionary. However, I am continually receiving a key error in my implementation, and I can't figure out why.
# Based on this answer: https://stackoverflow.com/questions/9807634/find-all-occurrences-of-a-key-in-nested-dictionaries-and-lists
def has_key_value(data, target):
for key, value in data.items():
if isinstance(value, dict):
yield from has_key_value(value, target)
elif key == target:
return true
for x in range(1, len(some_dict)):
if has_key_value(x, 'some status'):
#print the dictionary
I've gotten this far, but I can't for the life of me figure out how to return the contents of the dictionary in the nested some_dict. I have tried several things and finally came to this which sort of works:
for x in range(1, len(some_dict)):
if has_key_value(x, 'some status'):
print(some_dict[x])
Except after the first 3 dictionaries being printed it throws a 'KeyError: 4' error. I have checked that all the dictionaries within some_dict are identical in their schema so I can't figure out why the error. Thoughts?