Ways to Add Items to Dictionary in Python


Add Items to Dictionary

In this tutorial, we will discuss the various ways to add items to the dictionary.

Add Items to 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.

In [1]:
emp_details = {'first_name':'Tim', 'emp_id':200}
emp_details['Country'] = 'USA'
print(emp_details)
{'first_name': 'Tim', 'emp_id': 200, 'Country': 'USA'}

Updating Name.

In [2]:
emp_details = {'first_name':'Tim', 'emp_id':200}
emp_details['first_name'] = 'Tom'
print(emp_details)
{'first_name': 'Tom', 'emp_id': 200}

Key without value.

In [3]:
emp_details = {'first_name':'Tim', 'emp_id':200}
emp_details['last_name'] = None
print(emp_details)
{'first_name': 'Tim', 'emp_id': 200, 'last_name': None}

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.

In [1]:
emp_details = {'first_name':'Tim', 'emp_id':200}
emp_details.update({'emp_id': 300, "Country":"USA"})
print(emp_details)
{'first_name': 'Tim', 'emp_id': 300, 'Country': 'USA'}

Update to join dictionaries.

In [2]:
dict1 = {1:"one", 2:"Two"}
dict2 = {3:"Three", 4:"Four"}

dict1.update(dict2)

print(dict1)
{1: 'one', 2: 'Two', 3: 'Three', 4: 'Four'}

Update with nested list

In [3]:
dict1 = {1:"one", 2:"Two"}
dict2 = [[3,"Three"], [4,"Four"]]

dict1.update(dict2)

print(dict1)
{1: 'one', 2: 'Two', 3: 'Three', 4: 'Four'}

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.

In [1]:
dict1 = {1:"one", 2:"Two"}

dict1 = {**dict1, **{3:"Tree"}}

print(dict1)
{1: 'one', 2: 'Two', 3: 'Tree'}

Updating Item.

In [2]:
dict1 = {1:"one", 2:"Two"}

dict1 = {**dict1, **{3:"Three"}}

print(dict1)
{1: 'one', 2: 'Two', 3: 'Three'}

Merging Dictionaries

In [3]:
dict1 = {1:"one", 2:"Two"}
dict2 = {3:"Three", 4:"Four"}

dict1 = {**dict1, **dict2}

print(dict1)
{1: 'one', 2: 'Two', 3: 'Three', 4: 'Four'}

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.

In [1]:
dict1 = {1:"one", 2:"Two"}
numbers_list = ["Three", "Four"]

for i, value in enumerate(numbers_list, start  = 3):
    dict1[i] = value

print(dict1)
{1: 'one', 2: 'Two', 3: 'Three', 4: 'Four'}

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.

In [1]:
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)
{1: 'one', 2: 'Two', 3: 'Three', 4: 'Four'}

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.

In [1]:
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)
{1: 'One', 2: 'Two'}

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.

In [1]:
dict1 = {1:"one", 2:"Two"}

dict1.__setitem__(3,"Tree")

print(dict1)
{1: 'one', 2: 'Two', 3: 'Tree'}

Updating value of 3.

In [2]:
dict1.__setitem__(3,"Three")

print(dict1)
{1: 'one', 2: 'Two', 3: 'Three'}

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.

In [1]:
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)
{1: 'one', 2: 'Two', 3: 'Three', 4: 'Four'}

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.

In [1]:
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)
{1: 'one', 2: 'Two', 3: 'Three', 4: 'Four'}

Copy Dictionary

There are two ways to copy the content of the dictionary:

  1. Using copy() method.
  2. 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.

In [1]:
emp_details1 = {'first_name':'Tim', 'emp_id':200}
emp_details2 = emp_details1

emp_details1['emp_id'] = 300
print(emp_details2)
{'first_name': 'Tim', 'emp_id': 300}

Using copy() method. On updating emp_id of emp_details1, there is no impact on emp_details2.

In [2]:
emp_details1 = {'first_name':'Tim', 'emp_id':200}
emp_details2 = emp_details1.copy()

emp_details1['emp_id'] = 300
print(emp_details2)
{'first_name': 'Tim', 'emp_id': 200}

Using dict() function. On updating emp_id of emp_details1, there is no impact on emp_details2.

In [3]:
emp_details1 = {'first_name':'Tim', 'emp_id':200}
emp_details2 = dict(emp_details1)

emp_details1['emp_id'] = 300
print(emp_details2)
{'first_name': 'Tim', 'emp_id': 200}

References

  1. How to Add an Item to a Dictionary in Python
  2. Add and update an item in a dictionary in Python