In one of my previous articles we were talking about the pop and popitem dictionary methods. Today we’ll be talking about the get method.
Here’s the video version of the article:
The method get(key) may be used to access the value corresponding to key. It works like the [] operator if the key is found. Let’s define a dictionary:
>>> locations = {"Mexico" : "North America", "Chile" : "South America", "Estonia" : "Europe", "China" : "Asia"}
First let’s access one of its elements using square brackets:
>>> locations["Chile"]
'South America'
The same can be achieved by means of the get method:
>>> locations.get("Chile")
'South America'
If the key is not found, the [] operator raises an error whereas get returns None:
>>> locations["Peru"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'Peru'
>>> locations.get("Peru")
>>> print(locations.get("Peru"))
None
Default Value
There is also a version with 2 parameters: get(key, value). We can use it to set a default value, which will be returned, if the key is not found.
>>> locations.get("Peru", "South America")
'South America'
If the key is found, the method get(key, value) will not return the value from the parameter, but the one from the dictionary:
>>> locations.get("Estonia", "North America")
'Europe'