pythondictionarynestednested-properties

How to get nested dictionary key value with .get()


With a simple dictionary like:

myDict = {'key1':1, 'key2':2}

I can safely use:

print myDict.get('key3')

and even while 'key3' is not existent no errors will be thrown since .get() still returns None.

Now how would I achieve the same simplicity with a nested keys dictionary:

myDict={}
myDict['key1'] = {'attr1':1,'attr2':2}

The following will give a KeyError:

print myDict.get('key1')['attr3']

This will go through:

print myDict.get('key1').get('attr3')

but it will fail with adn AttributeError: 'NoneType' object has no attribute 'get':

print myDict.get('key3').get('attr1')

Solution

  • dict.get accepts additional default parameter. The value is returned instead of None if there's no such key.

    print myDict.get('key1', {}).get('attr3')