How to Add Value to Dictionary in Python
To add value to a dictionary in Python, you can use different methods like the = assignment operator, the update() function, or the setdefault() function.
The following examples show how to add value to a dictionary using different methods.
Using = Operator
We can use the assignment operator (=) to add a value to a dictionary.
Suppose we have the following dictionary:
# Create dictionary
dictionary1 = {"A": 25, "B": 27, "C": 45}
# Add value to dictionary
dictionary1["D"] = 36
# Show dictionary
print("Dictionary:", dictionary1)
Output: 👇️
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 dictionary1.
Using update() Function
We can use the update() function to add a value to a dictionary.
Suppose we have the following dictionaries:
# Create dictionaries
dictionary1 = {"A": 25, "B": 27, "C": 45}
dictionary2 = {"D": 36}
# Add value to dictionary
dictionary1.update(dictionary2)
# Show dictionary
print("Dictionary:", dictionary1)
Output: 👇️
Dictionary: {'A': 25, 'B': 27, 'C': 45, 'D': 36}
In this example, we use the update() function to add the key-value pair from dictionary2 to dictionary1.
Using setdefault() Function
The setdefault() method adds a new key-value pair only if the key does not already exist. If the key already exists, it returns the existing value without modifying the dictionary.
Suppose we have the following dictionary:
# Create dictionary
dictionary1 = {"A": 25, "B": 27, "C": 45}
# Add value to dictionary
dictionary1.setdefault("D", 36)
# Show dictionary
print("Dictionary:", dictionary1)
Output: 👇️
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 dictionary1.