Skip to content

Instantly share code, notes, and snippets.

@dpfrakes
Created October 15, 2019 16:37
Show Gist options
  • Save dpfrakes/01710ca5a76220ef1d0a710451f1d4d5 to your computer and use it in GitHub Desktop.
Save dpfrakes/01710ca5a76220ef1d0a710451f1d4d5 to your computer and use it in GitHub Desktop.
Find key or value recursively in python dict
def find_k(data, target, spec=0):
result = ''
found = False
for k, v in data.items():
print(f'{"\t" * spec}{k}: {type(v)}')
if isinstance(v, dict):
search, found = find_k(v, target, spec+1)
result = f'{k} > {search}'
elif k == target:
found = True
result = k
if found:
break
return result, found
def find_v(data, target, spec=0):
result = ''
found = False
for k, v in data.items():
print(f'{"\t" * spec}{k}: {type(v)}')
if isinstance(v, dict):
search, found = find_v(v, target, spec+1)
result = f'{k} > {search}'
elif isinstance(v, list):
search, found = find_v(v[0], target, spec+1)
result = f'{k}[0] > {search}'
elif v == target:
found = True
result = k
if found:
break
return result, found
find_v(d, v)[0]
find_v(d1, 25.0)[0]
find_v(d2, 15.0)[0]
sample_dict = {
'firstName': 'Dan',
'lastName': 'Frakes',
'address': {
'street': 'Main St',
'number': '123',
'apt': 'Apt B',
'zip': 12345,
'city': 'Alexandria',
'state': 'VA',
},
'contact': {
'phone': '20212345567',
'email': 'asdfjkl@gmail.com',
}
}
sample_target = 'VA'
find_v(sample_dict, sample_target)[0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment