Skip to content

Instantly share code, notes, and snippets.

@belsander
Last active May 3, 2018 14:26
Show Gist options
  • Save belsander/9ddcc7f5569540f26dc106cc1412155b to your computer and use it in GitHub Desktop.
Save belsander/9ddcc7f5569540f26dc106cc1412155b to your computer and use it in GitHub Desktop.
Find all occurences of a key in a nested Python dictionary and return the occurences together with the keys
def find(find_object, result, keys=[]):
if isinstance(find_object, dict):
for key, value in find_object.iteritems():
find(value, result, keys + [key])
else:
if not(result):
result['values'] = [find_object]
result['keys'] = [keys]
else:
result['values'].append(find_object)
result['keys'].append(keys)
# Example 1
dict_example1 = {'key1': {'key1.1': ['value1.1.1','value1.1.2']},
'key2': 'value2',
'key3': {'key3.1': 'value3.1', 'key3.2': 'value3.2'},
'key4': ['value4.1', 'value4.2'],
'key5': {'key5.1': {'key5.1.1': ['value5.1.1.1']}}
}
# A result dictionary has to be provided, if this dictionary is
# declared in the function itself, the same object in memory keeps
# being addressing
result_example1 = {}
find(dict_example1, result_example1)
for i in range(len(result_example1['keys'])):
print("keys: %s; values: %s" % (result_example1['keys'][i],
result_example1['values'][i]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment