Last active
August 2, 2020 13:54
-
-
Save raeq/3ac73f1258058ff3f747b1987992c870 to your computer and use it in GitHub Desktop.
Get index pertaining to a value in nested dictionary
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_key_by_value(dictionary: dict, val: str) -> object: | |
"""get_values_by_key. | |
Args: | |
dictionary (dict): dictionary | |
val (str): value | |
Returns: | |
dict: | |
""" | |
if isinstance(dictionary, dict): | |
for k, v in dictionary.items(): | |
if val == v: | |
yield k | |
elif isinstance(v, dict): | |
for result in get_key_by_value(v, val): | |
yield result | |
elif isinstance(v, list): | |
for list_item in v: | |
for result in get_key_by_value(list_item, val): | |
yield result | |
dict1 = dict( | |
json.loads( | |
requests.get("http://ergast.com/api/f1/2004/1/results.json").text)) | |
assert "raceName" in list(get_key_by_value(dict1, "Australian Grand Prix")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment