Introduction
Dictionaries are Python's built-in data types for storing key-value pairs. The dictionary elements are changeable and don't allow duplicates. In Python 3.7 and higher, dictionary items are ordered. Lower versions of Python treat dictionary elements as unordered.
Depending on the desired result and given data, there are various ways to add items to a dictionary.
This guide shows how to add items to a Python dictionary through examples.
Prerequisites
- Python version 3.7 or higher.
- A text editor or IDE to write code.
- A method to run the code, such as a terminal or IDE.
How to Add an Item to a Dictionary in Python
To test out different methods of adding items to a dictionary, create a dictionary with two items. Use the following code:
my_dictionary = {
"one": 1,
"two": 2
}
The methods below show how to add one or multiple items to a Python dictionary.
Note: Adding an item with an existing key replaces the dictionary item with a new value. Make sure to provide unique keys to avoid overwriting data.
Method 1: Using The Assignment Operator
The assignment operator sets a value to a key using the following syntax:
dictionary_name[key] = value
The assignment operator adds a new key-value pair if the key does not exist.
The following code demonstrates how to add an item to a Python dictionary using the assignment operator:
my_dictionary = {
"one": 1,
"two": 2
}
print("Before:", my_dictionary)
my_dictionary["tree"] = 3
print("After:", my_dictionary)
The code outputs the dictionary contents before and after adding a new item.
Method 2: Using update()
The update()
method updates an existing dictionary with a new dictionary item:
dictionary_name.update({key:value})
The method accepts one or multiple key-value pairs, which is convenient for adding more than one element.
The example code looks like the following:
my_dictionary = {
"one": 1,
"two": 2
}
print("Before:", my_dictionary)
my_dictionary.update({"three":3})
print("After:", my_dictionary)
Use this method to add multiple new items or append a dictionary to an existing one.
Method 3: Using __setitem__
The __setitem__
method is another way to append a new dictionary item:
dictionary_name.__setitem__(key,value)
For example:
my_dictionary = {
"one": 1,
"two": 2
}
print("Before:", my_dictionary)
my_dictionary.__setitem__("three", 3)
print("After:", my_dictionary)
The method sets the item key as "three"
with the value 3
.
Method 4: Using The ** Operator
The **
operator helps merge an existing dictionary into a new dictionary and adds additional items. The syntax is:
new_dictionary = {**old_dicitonary, **{key:value}}
For example, to copy an existing dictionary and append a new item to a new one, see the following code:
my_dictionary = {
"one": 1,
"two": 2
}
my_new_dictionary = {**my_dictionary, **{"three":3}}
print("Old:", my_dictionary)
print("New:", my_new_dictionary)
The new dictionary contains the added item, preserving the old dictionary values. Use this method to avoid changing existing dictionaries.
Method 5: Checking If A Key Exists
Use an if
statement to check whether a key exists before adding a new item to a dictionary. The example syntax is:
if key not in dictionary_name:
dictionary_name[key] = value
For example:
my_dictionary = {
"one": 1,
"two": 2
}
print("Before:", my_dictionary)
if "three" not in my_dictionary:
my_dictionary["three"] = 3
print("After:", my_dictionary)
The code checks whether a key with the provided name exists before adding the item to the dictionary. If the provided key exists, the existing key value does not update, and the dictionary stays unchanged.
Method 6: Using A For Loop
Add key-value pairs to a nested list and loop through the list to add multiple items to a dictionary. For example:
my_dictionary = {
"one": 1,
"two": 2
}
my_list = [["three", 3], ["four", 4]]
print("Before:", my_dictionary)
for key,value in my_list:
my_dictionary[key] = value
print("After:", my_dictionary)
The for
loop goes through the pairs inside the list and adds two new elements.
Note: For loop and a counter are also used as one of the methods to identify the length of a list. Learn more by visiting our guide How to Find the List Length in Python.
Method 7: Using zip
Use zip
to create key-value pairs from two lists. The first list contains keys and the second contains the values.
For example:
my_dictionary = {
"one": 1,
"two": 2
}
my_keys = ["three", "four"]
my_values = [3, 4]
print("Before:", my_dictionary)
for key,value in zip(my_keys, my_values):
my_dictionary[key] = value
print("After:", my_dictionary)
The zip
function matches elements from two lists by index, creating key-value pairs.
How to Update a Python Dictionary
Update Python dictionary values using the same syntax as adding a new element. Provide the key name of an existing key, for example:
my_dictionary = {
"one": 1,
"two": 2
}
print("Before:", my_dictionary)
my_dictionary["one"] = 3
print("After:", my_dictionary)
Since Python does not allow duplicate entries in a dictionary, the code updates the value for the provided key and overwrites the existing information.
Conclusion
After going through the examples in this tutorial, you know how to add items to a Python dictionary. All methods provide unique functionalities, so choose a way that best suits your program and situation.
For more Python tutorial refer to our article and find out how to pretty print a JSON file using Python.