Add Items to Dictionary
In this tutorial, we will discuss the various ways to add items to the dictionary.
Assigning value to key
We can create a new key-value pair by simply assigning value to the key. If the key already exists in the dictionary, it will update its value, else it will create the new key-value pair.
In case a key is needed without value, it is assigned to the “None”.
Adding new item ‘Country’ to the dictionary.
emp_details = {'first_name':'Tim', 'emp_id':200}
emp_details['Country'] = 'USA'
print(emp_details)
Updating Name.
emp_details = {'first_name':'Tim', 'emp_id':200}
emp_details['first_name'] = 'Tom'
print(emp_details)
Key without value.
emp_details = {'first_name':'Tim', 'emp_id':200}
emp_details['last_name'] = None
print(emp_details)
The update() Method
The update() in the built-in method that can be used to add an item to the dictionary as well as update an item in the dictionary.
We pass a comma separated key : value pair to the update() method. If the key already exists, then it will update its value, else will add a new pair.
This approach can also be used to join two dictionaries and works with nested iterable. For example, nested list used in the below example.
Existing key emp_id gets updated and the new key Country gets added.
emp_details = {'first_name':'Tim', 'emp_id':200}
emp_details.update({'emp_id': 300, "Country":"USA"})
print(emp_details)
Update to join dictionaries.
dict1 = {1:"one", 2:"Two"}
dict2 = {3:"Three", 4:"Four"}
dict1.update(dict2)
print(dict1)
Update with nested list
dict1 = {1:"one", 2:"Two"}
dict2 = [[3,"Three"], [4,"Four"]]
dict1.update(dict2)
print(dict1)
Using the ** Operator
The ** operator is mainly used to merge dictionaries. We can also make it work to add an item by passing the key-value pair in dictionary format. The below examples will make it more clear.
Adding Item.
dict1 = {1:"one", 2:"Two"}
dict1 = {**dict1, **{3:"Tree"}}
print(dict1)
Updating Item.
dict1 = {1:"one", 2:"Two"}
dict1 = {**dict1, **{3:"Three"}}
print(dict1)
Merging Dictionaries
dict1 = {1:"one", 2:"Two"}
dict2 = {3:"Three", 4:"Four"}
dict1 = {**dict1, **dict2}
print(dict1)
Using the enumerate() function
Python has a built-in function to loop over an iterable like list, tuple, etc. It keeps the track of the index and the corresponding element in each iteration. We can provide a start value to the enumerate() function to make it start from a custom index. In the below example, we will add the elements of the list to the dictionary using enumerate.
dict1 = {1:"one", 2:"Two"}
numbers_list = ["Three", "Four"]
for i, value in enumerate(numbers_list, start = 3):
dict1[i] = value
print(dict1)
Using zip() function
When we need to iterate over two or more iterators at the same time, the zip() function is used. Tuples having one element from each iterator are retuned. We can use the data of these tuples as key and value for a dictionary.
dict1 = {1:"one", 2:"Two"}
numbers = [3, 4]
numbers_list = ["Three", "Four"]
for i, value in zip(numbers, numbers_list):
dict1[i] = value
print(dict1)
Using the custom Class
We can create a custom class which inherits the built-in dict class. The __init__() method is there to initialize the empty dictionary, and the add_number() method is created to add items to the dictionary.
class my_numbers(dict):
def __init__(self):
self = dict()
# function to add key-value pair
def add_number(self, key, value):
self[key] = value
numbers = my_numbers()
numbers.add_number(1, 'One')
numbers.add_number(2, 'Two')
print(numbers)
Using the __setitem__ Method
This method is not commonly used because of its poor performance, but it is good to know about it.
The comma separated key and value are passed as an argument. Again, if the key does not exist, it gets added, and if it exists, its value will be updated.
Adding a new key-value pair.
dict1 = {1:"one", 2:"Two"}
dict1.__setitem__(3,"Tree")
print(dict1)
Updating value of 3.
dict1.__setitem__(3,"Three")
print(dict1)
Using for loop
A nested list can have the key-value pairs of the elements. The for loop will iterate over the list and unpack each child list.
dict1 = {1:"one", 2:"Two"}
numbers_list = [[3,"Three", "T"], [4,"Four","F"]]
for i,j,k in numbers_list:
dict1[i] = j
print(dict1)
Without overwriting existing value
To add the data to the dictionary without overwriting the existing values, simply membership test has to be performed using the “if” statement before adding data to the dictionary.
dict1 = {1:"one", 2:"Two"}
numbers_list = [[2,"To", "To"], [3,"Three", "Th"], [4,"Four","Fo"]]
for i,j,k in numbers_list:
if i not in dict1:
dict1[i] = j
print(dict1)
Copy Dictionary
There are two ways to copy the content of the dictionary:
- Using copy() method.
- Using dict() function.
We should not copy the dictionary using the = operator. It will not copy the dictionary, just create the reference. On updating the value at the first one, the second will also get updated.
Using = operator. On updating emp_id of emp_details1, emp_details2 also gets updated, which is wrong.
emp_details1 = {'first_name':'Tim', 'emp_id':200}
emp_details2 = emp_details1
emp_details1['emp_id'] = 300
print(emp_details2)
Using copy() method. On updating emp_id of emp_details1, there is no impact on emp_details2.
emp_details1 = {'first_name':'Tim', 'emp_id':200}
emp_details2 = emp_details1.copy()
emp_details1['emp_id'] = 300
print(emp_details2)
Using dict() function. On updating emp_id of emp_details1, there is no impact on emp_details2.
emp_details1 = {'first_name':'Tim', 'emp_id':200}
emp_details2 = dict(emp_details1)
emp_details1['emp_id'] = 300
print(emp_details2)