python==3.8.5
Python Dictionary - Multiple ways to get items
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.
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.
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.
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.
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'}