Skip to content

Instantly share code, notes, and snippets.

@lokesh1729
Created March 26, 2019 10:42
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 lokesh1729/c28f4697990d11951f36869aefcf171e to your computer and use it in GitHub Desktop.
Save lokesh1729/c28f4697990d11951f36869aefcf171e to your computer and use it in GitHub Desktop.
Get Nested Values from dict
def get_nested_values_from_dict(data, attrs, index=0):
"""
get values from nested dictionary
Example:
>>> data = {"a": {"b": {"c": 3}}
>>> get_nested_values_from_dict(data, ["a", "b", "c"])
>>> 3
:param data: dict
:param attrs: list
:param index: int
:return:
"""
if index >= len(attrs):
return data
try:
return get_nested_values_from_dict(
data.get(attrs[index]), attrs, index + 1
)
except AttributeError:
raise ValueError("Invalid parameters passed")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment