Last active
May 3, 2021 22:05
-
-
Save citadelgrad/56bdd723cf1e13501639dfc3a2157901 to your computer and use it in GitHub Desktop.
Find all occurrences of a key in nested dictionaries and lists
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
# 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