python==3.8.5
Python Dictionary - Multiple ways to get items
python, fstrings, formatting, tips
About
This notebook demonstrates multiple ways to get items from a Python dictionary.
Environment Details
Example Dictionaries
{'brand': 'ford', 'model': 'mustang'}
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
Problem with this approach is that if the provided key is not available in the dictionary then it will throw a KeyError exception.
KeyErrorTraceback (most recent call last) <ipython-input-5-ca220af55913> in <module> ----> 1 car['year'] KeyError: 'year'
To avoid KeyError, you can first check if the key is available in dictionary.
'1964'
An alternate approach could be to use a Try-Except block to handle the KeyError exception.
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.
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.
'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.
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.
{'love': 'python'}
AttributeErrorTraceback (most recent call last) <ipython-input-14-a35a8f091991> in <module> 1 # this will NOT work. 'mother' key is missing and it returned a default None value. 2 # but since it is not at the end, and we called Get function on returned value 'None' ----> 3 family.get('gfather').get('mother').get('son') AttributeError: 'NoneType' object has no attribute 'get'