Skip to content

Instantly share code, notes, and snippets.

@rummykhan
Last active November 23, 2016 13:00
Show Gist options
  • Save rummykhan/a17dcd5a5736acc64c1d879328a3634d to your computer and use it in GitHub Desktop.
Save rummykhan/a17dcd5a5736acc64c1d879328a3634d to your computer and use it in GitHub Desktop.
Get value from dictionary using dot syntax Python
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