Last active
November 23, 2016 13:00
-
-
Save rummykhan/a17dcd5a5736acc64c1d879328a3634d to your computer and use it in GitHub Desktop.
Get value from dictionary using dot syntax Python
This file contains 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(dictionary, key): | |
tmp = key.split('.', 1) | |
if dictionary.get(tmp[0], None) is None: | |
return None | |
if len(tmp) > 1 and tmp[1] is not False: | |
return get(dictionary.get(tmp[0]), tmp[1]) | |
if dictionary.get(tmp[0], None) is None: | |
return None | |
return dictionary.get(tmp[0]) | |
''' | |
_dict = { | |
"name": "Vin Desil", | |
"age": "34", | |
"movies": { | |
"name": "XXX", | |
"year": "2008", | |
"awards": { | |
"academy": False, | |
"oscar": False | |
} | |
} | |
} | |
try: | |
print(get(_dict, 'movies.name.awards')) | |
except: | |
print('# Invalid Key.') | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment