Skip to content

Instantly share code, notes, and snippets.

@sapamja
Created September 22, 2014 21:42
Show Gist options
  • Save sapamja/fe2903c8ac7f59f2806a to your computer and use it in GitHub Desktop.
Save sapamja/fe2903c8ac7f59f2806a to your computer and use it in GitHub Desktop.
dictionary get for nested dictionary
>>>
>>> d = {
... 'key1' : {
... 'value': "parent-key1",
... 'subkey1': {
... 'value': "child1"
... },
... 'subkey2': {
... 'value': "child2"
... }
... },
... 'key2': {
... 'value': "parent-key2",
... 'subkey1': {
... 'value': "child3"
... },
... 'subkey2': {
... 'value': "child4"
... }
... }}
>>>
>>> def get_value(key, subkey):
... dkey = d.get(key)
... return dkey.get(subkey, {}).get('value', dkey.get('value'))
...
>>> print get_value("key1", "subkey1")
child1
>>> print get_value("key2", "subkey2")
child4
>>> print get_value("key2", "subkey3")
parent-key2
>>>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment