How to Add Key Value Pair to Dictionary in Python
To add a key-value pair to a dictionary in Python, you can use three different methods.
The following examples show how to add a key-value pair to a dictionary in Python.
Using = Operator
We can use the assignment (=) operator to add a key-value pair to a dictionary.
Suppose we have the following dictionary:
# Declare dictionary
dict1 = {"A": 25, "B": 27, "C": 45}
# Add key-value pair
dict1["D"] = 36
# Show updated dictionary
print("Updated dictionary:", dict1)
Output: 👇️
Updated dictionary: {'A': 25, 'B': 27, 'C': 45, 'D': 36}
In this example, we use the assignment (=) operator to add the key-value pair “D”: 36 to the dictionary.
Using update() Function
We can use the update() function to add a key-value pair to a dictionary.
Suppose we have the same dictionary as above.
We can use the following code to add the key-value pair “D”: 36 to the dictionary:
# Add key-value pair
dict1.update({"D": 36})
# Show updated dictionary
print("Updated dictionary:", dict1)
Output: 👇️
Updated dictionary: {'A': 25, 'B': 27, 'C': 45, 'D': 36}
In this example, we use the update() function to add the key-value pair “D”: 36 to the dictionary.
Using setdefault() Function
We can use the setdefault() function to add a key-value pair to a dictionary.
Suppose we have the same dictionary as above.
We can use the following code to add the key-value pair “D”: 36 to the dictionary:
# Add key-value pair
dict1.setdefault("D", 36)
# Show updated dictionary
print("Updated dictionary:", dict1)
Output: 👇️
Updated dictionary: {'A': 25, 'B': 27, 'C': 45, 'D': 36}
In this example, we use the setdefault() function to add the key-value pair “D”: 36 to the dictionary.