Summary: When working with Python dictionaries, in some cases you may want to access a specific value of a certain item, this is where the dict.get() method comes in handy.
Definition: Python’s dict.get() method expects a key argument. If the specified key is in the dictionary, the method will output the value associated with the key.
Syntax of dict.get() Method
Method Declaration of dict.get():
dict.get(key, optional_value)
The two parameters of dict.get():
- Key: The
keythat thedict.get()method searches for in the dictionary. - Optional Value: The
optional_valueis the value output, if the key is not found in the dictionary, the value defaults toNoneifoptional_valueisn’t specified.
Output Value of dict.get():
The dict.get() method returns the associated value of the specified key if the key is in the dictionary, otherwise, the default value None or the optional_value that was passed as an argument to the dictionary gets returned.
Basic Exampleof dict.get() Method
grades_dict = {'programming': 83, 'math': 85, 'science': 80}
print(grades_dict.get('programming'))
# 83Accessing Nested Dictionary Key Values
Here’s how you accidentally define a dictionary with three identical keys:
# Define nested dictionary:
employee_dict = {'id_1': {'name': 'bob', 'age': 20, 'profession': 'programmer'},
'id_2': {'name': 'tammy', 'age': 25, 'profession': 'engineer'},
'id_3': {'name': 'dylan', 'age': 30, 'profession': 'nurse'}}
print(employee_dict)Output:
{'id_1': {'name': 'bob', 'age': 20, 'profession': 'programmer'},
'id_2': {'name': 'tammy', 'age': 25, 'profession': 'engineer'},
'id_3': {'name': 'dylan', 'age': 30, 'profession': 'nurse'}}This code snippet declares a regular dictionary along with three nested dictionaries, each dictionary can then be accessed by its corresponding key.
# How to access the elements of a nested dictionary:
# list employee names:
id1_employee = employee_dict.get('id_1', {}).get('name')
id2_employee = employee_dict.get('id_2', {}).get('name')
id3_employee = employee_dict.get('id_3', {}).get('name')
print(id1_employee)
# bob
print(id2_employee)
# tammy
print(id3_employee)
# dylan
Difference dict.get() and dict[key] when Accessing Dictionary Elements
# Empty Dictionary Example
empty_dict = {}
# Applying dict.get() method to an empty dictionary:
print(empty_dict.get('key'))
# NoneNow, let’s try to get a key from an empty dictionary using the standard square bracket method to index a non-existent key:
# Applying dict[] to an empty dictionary. # This results in a keyError being returned: print(empty_dict['key'])
This results in the following error message that could’ve been prevented with dict.get():
Traceback (most recent call last):
File "C:\Users\xcent\Desktop\code.py", line 11, in <module>
print(empty_dict['key'])
KeyError: 'key'