Created
August 2, 2020 12:13
-
-
Save raeq/315a82fe17c717633c6699e47fc70cdd to your computer and use it in GitHub Desktop.
Find all nested keys in a dict
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
import json | |
import requests | |
def get_values_by_key(dictionary: dict, key: str) -> dict: | |
"""get_values_by_key. | |
Args: | |
dictionary (dict): dictionary | |
key (str): key | |
Returns: | |
dict: | |
""" | |
if isinstance(dictionary, dict): | |
for k, v in dictionary.items(): | |
if k == key: | |
yield v | |
elif isinstance(v, dict): | |
for result in get_values_by_key(v, key): | |
yield result | |
elif type(v) in (list, tuple): | |
for d in v: | |
for seq in get_values_by_key(d, key): | |
if type(seq) in (list, tuple): | |
for inner_item in seq: | |
yield inner_item | |
else: | |
yield seq | |
dict1 = dict( | |
json.loads( | |
requests.get("http://ergast.com/api/f1/2004/1/results.json").text)) | |
assert "http://en.wikipedia.org/wiki/McLaren" in list( | |
get_values_by_key(dict1, "url")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment