Created
March 26, 2019 10:42
-
-
Save lokesh1729/c28f4697990d11951f36869aefcf171e to your computer and use it in GitHub Desktop.
Get Nested Values from 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
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