Skip to content

Instantly share code, notes, and snippets.

@alan-ho
Last active July 22, 2023 07:15
Show Gist options
  • Select an option

  • Save alan-ho/ba49299b771a4d847da4fb64591e9fbc to your computer and use it in GitHub Desktop.

Select an option

Save alan-ho/ba49299b771a4d847da4fb64591e9fbc to your computer and use it in GitHub Desktop.
Find value of key in a nested dictionary in Python
def find_key_in_nested_dict(d, target_key, path=None):
if path is None:
path = []
for key, value in d.items():
current_path = path + [key]
if key == target_key:
return current_path
if isinstance(value, dict):
found = find_key_in_nested_dict(value, target_key, current_path)
if found:
return found
return None
# Example usage
target_key = "Germany"
nested_dict = {
# ... (your provided nested dictionary) ...
}
result = find_key_in_nested_dict(nested_dict, target_key)
if result:
print(f"Key '{target_key}' found at path: {' -> '.join(result)}")
else:
print(f"Key '{target_key}' not found in the dictionary.")
# Nested dictionary search
nested = {'a':1,
'b':2,
'c': {'aa': 11,
'bb': {'aaa': 111}
},
'd':3
}
def find_me(target_key, layered_dict):
for key in layered_dict:
if key == target_key:
return layered_dict[key]
elif type(layered_dict[key]) == dict:
value = find_me(target_key, layered_dict[key])
if value != None:
return value
find_me('bb', nested)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment