Skip to content

Instantly share code, notes, and snippets.

@raeq
Last active August 2, 2020 13:54
Show Gist options
  • Save raeq/3ac73f1258058ff3f747b1987992c870 to your computer and use it in GitHub Desktop.
Save raeq/3ac73f1258058ff3f747b1987992c870 to your computer and use it in GitHub Desktop.
Get index pertaining to a value in nested dictionary
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