Python Dictionary - Multiple ways to get items

python
A tutorial on multiple ways to get items from a Python dictionary.
Published

February 10, 2022

About

This notebook demonstrates multiple ways to get items from a Python dictionary.

Environment Details

Code
from platform import python_version

print("python==" + python_version())
python==3.8.5

Example Dictionaries

##
# simple dictionary
car = {
    "brand": "ford",
    "model": "mustang"
}

car
{'brand': 'ford', 'model': 'mustang'}
##
# nested dictionary
family = {
    'gfather' : {
        'father': {
            'son': {'love':'python'}
        }
    }
}

family
{'gfather': {'father': {'son': {'love': 'python'}}}}

Method 1: Square brackets

A square bracket is the simplest approach to getting any item from a dictionary. You can get a value from a dictionary by providing it a key in [] brackets. For example, to get a value of model from a car

car['model']
'mustang'

Problem with this approach is that if the provided key is not available in the dictionary then it will throw a KeyError exception.

car['year']
KeyError: 'year'

To avoid KeyError, you can first check if the key is available in dictionary.

if 'year' in car: # check if given key is available in dictionary
    year = car['year'] # now get the value
else:
    year = '1964' # (Optional) otherwise give this car a default value

year
'1964'

An alternate approach could be to use a Try-Except block to handle the KeyError exception.

try:
    year = car['year']
except KeyError:
    year = '1964' # give this car a default value

year
'1964'

For nested dictionaries, you can use chained [] brackets. But beware that if any of the Keys is missing in the chain, you will get a KeyError exception.

##
# this will work. All keys are present.
family['gfather']['father']['son']
{'love': 'python'}
##
# this will not work. 'mother' key is not in dictionary
family['gfather']['mother']['son']
KeyError: 'mother'

Method 2: Get function

https://docs.python.org/3/library/stdtypes.html#dict.get
get(key[, default])

Get function will return the value for key if key is in the dictionary. Otherwise, it will return a default value which is None. You can provide your default value as well.

year = car.get('year', '1964')
year
# year key is not present so get function will return a default value '1964'
'1964'

Depending on your use case there can be confusion with this approach when your item can also have None value. In that case, you will not know whether the None value was returned from the dictionary or it was the Get function.

owner = car.get('owner')
owner
# owner has a None value. But is this value coming from dic or from Get function? 
# This can be confusing for large nested dictionaries.

For nested dictionaries you can use chained Get functions. But beware that missing Key items needs to be properly handled otherwise you will still get an exception.

##
# this will work. All keys are present.
family.get('gfather').get('father').get('son')
{'love': 'python'}
##
# this will still work. 'daughter' key is missing
# but since it is at the end of chain it will return a default None value
family.get('gfather').get('father').get('daughter')
##
# this will NOT work. 'mother' key is missing and it returned a default None value.
# but since it is not at the end, and we called Get function on returned value 'None'
family.get('gfather').get('mother').get('son')
AttributeError: 'NoneType' object has no attribute 'get'
##
# this will work. 'mother' key is missing and it returned a default value.
# but we have properly handled all the default values with empty dictionaries.
family.get('gfather', {}).get('mother', {}).get('son', {})
{}