How to Add Element to a Dictionary in Python
Adding an element to a dictionary in Python involves adding a new key-value pair. To add an element to a dictionary, you can use different methods.
The following examples show how to add an element to a dictionary in Python.
Using = & [] Operator
We can use the = and [] operators to add an element to a dictionary.
Suppose we have the following dictionary:
# Declare dictionary
dict1 = {1: "Mon", 2: "Tue", 3: "Wed"}
# Add element to dictionary
dict1[4] = "Thurs"
# Show updated dictionary
print("Updated dictionary:", dict1)
Output: 👇️
Updated dictionary: {1: 'Mon', 2: 'Tue', 3: 'Wed', 4: 'Thurs'}
In this example, we use the = and [] operators to add the key-value pair 4: “Thurs” to the dictionary.
Using update() Function
We can use the update() function to add an element to a dictionary.
Suppose we have the same dictionary as above.
We can use the following code to add the key-value pair 4: “Thurs” to the dictionary:
# Add element to dictionary
dict1.update({4: "Thurs"})
# Show updated dictionary
print("Updated dictionary:", dict1)
Output: 👇️
Updated dictionary: {1: 'Mon', 2: 'Tue', 3: 'Wed', 4: 'Thurs'}
In this example, we use the update() function to add the key-value pair 4: “Thurs” to the dictionary.
Using setdefault() Function
We can use the setdefault() function to add an element to a dictionary.
Suppose we have the same dictionary as above.
We can use the following code to add the key-value pair 4: “Thurs” to the dictionary:
# Add element to dictionary
dict1.setdefault(4, "Thurs")
# Show updated dictionary
print("Updated dictionary:", dict1)
Output: 👇️
Updated dictionary: {1: 'Mon', 2: 'Tue', 3: 'Wed', 4: 'Thurs'}
In this example, we use the setdefault() function to add the key-value pair 4: “Thurs” to the dictionary.