Skip to content

Instantly share code, notes, and snippets.

@erik4github
Last active July 24, 2019 14:27
Show Gist options
  • Save erik4github/66961ffdf65994f319f3813c09bfba9e to your computer and use it in GitHub Desktop.
Save erik4github/66961ffdf65994f319f3813c09bfba9e to your computer and use it in GitHub Desktop.
find where a nested key is located in the dictionary
example_dict = {
'hello': {
'world': {
'nest': 'end'
}
}
}
def find_key(d, value):
for k,v in d.items():
if isinstance(v, dict):
path = find_key(v, value)
if path:
return v
elif k == value:
return [k]
# returns {'world': {'nest': 'end'}}
# or
def find_key(d, value):
for k,v in d.items():
if isinstance(v, dict):
path = find_key(v, value)
if path:
result = [k] + p
elif k == value:
return [k]
# returns ['hello', 'world', 'nest']
print (find_key(example_dict,'nest'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment