
get() Method in dictionary –
The dictionary get method returns the value of a key if the key is in the dictionary.
Syntax of get method –
dict.get(key, value)
key – the key to search in the dictionary
value (optional) – value to return if key doesn’t exist. The default value is None.
Let’s say we have a dictionary which contains some information about a person.
In [1]: person = {'Name': 'Emma', 'Age': 25, 'Location': 'California'}
Now, we can us the get method to get the information about this person.
In [2]: person.get('Name')
Out[2]: 'Emma'
In [3]: person.get('Age')
Out[3]: 25
In [4]: person.get('Location')
Out[4]: 'California'
And if a key does not exist in the dictionary then python will return None or the default value we provide.
In [6]: person.get('Profession')
In [7]: person.get('Profession', "Profession doesn't exist")
Out[7]: "Profession doesn't exist"
What is the difference between dict.get(‘key’) vs dict[‘key’] ?
If we use dict[‘key’] and the key doesn’t exist in the dictionary then Python will throw KeyError.
In [8]: person['Profession']
Traceback (most recent call last):
File "C:\Users\BHOLA\AppData\Local\Temp\ipykernel_30100\2606145282.py", line 1, in <module>
person['Profession']
KeyError: 'Profession'
As we said before, if you use dict.get(‘key’) and key does not exist in the dictionary then python will return None or the default value.
In [9]: person.get('Profession')
In [10]: person.get('Profession', "Profession doesn't exist")
Out[10]: "Profession doesn't exist"