Created
April 4, 2019 09:32
-
-
Save aruseni/d13372c40d4a6c675ecf860aae4016f1 to your computer and use it in GitHub Desktop.
Gets a value following the specified path, if such value exists
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 deep_get(dictionary, keys, default=None): | |
""" | |
Gets a value following the specified path, if it exists. | |
The keys are dot-separated. | |
Example: | |
deep_get({'most_visited': {'url': 'https://test.com/'}}, 'most_visited.url') | |
""" | |
v = dictionary | |
for k in keys.split('.'): | |
if isinstance(v, dict) and k in v: | |
v = v[k] | |
else: | |
return default | |
return v |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment