Skip to content

Instantly share code, notes, and snippets.

@citadelgrad
Last active May 3, 2021 22:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save citadelgrad/56bdd723cf1e13501639dfc3a2157901 to your computer and use it in GitHub Desktop.
Save citadelgrad/56bdd723cf1e13501639dfc3a2157901 to your computer and use it in GitHub Desktop.
Find all occurrences of a key in nested dictionaries and lists
# Source: https://stackoverflow.com/questions/9807634/find-all-occurrences-of-a-key-in-nested-dictionaries-and-lists
# Python dict.iteritems became just dict.items.
# Easily coherse the generator into a list with: `list(gen_dict_extract("KeytoFind", MyDict))`
def gen_dict_extract(key, var):
if hasattr(var, 'items'):
for k, v in var.items():
if k == key:
yield v
if isinstance(v, dict):
for result in gen_dict_extract(key, v):
yield result
elif isinstance(v, list):
for d in v:
for result in gen_dict_extract(key, d):
yield result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment