Last active
July 24, 2019 14:27
-
-
Save erik4github/66961ffdf65994f319f3813c09bfba9e to your computer and use it in GitHub Desktop.
find where a nested key is located in the dictionary
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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