Python

Python dictionary update() method

Many built-in functions exist in python to work on dictionary objects or an iterable object that contains key-value pairs. The update() method is one of them. It is used to modify the content of the dictionary based on the key value. If the key exists, then the value of that key will be updated; otherwise, a new key-value pair will be inserted in the dictionary when the update() function is used for the dictionary. How this method works and the uses of this method have shown in this tutorial.

Syntax of Dictionary update() function:

The syntax of update() function has given below.

dic dict.update([other_dic] | iterable_object )

The argument of this function can be another dictionary, and the argument is optional. If no argument is used in this function, then the function will return the original dictionary; otherwise, the modified dictionary will return.

Different uses of update() function:

Example-1: Update the dictionary by adding values of another dictionary

Create a python file with the following script to add the key-value pairs of a dictionary on the end of another dictionary by using the update() function. Two dictionaries have been declared in the script. The dictionary named Dic_employees1 contains three key-value pairs, and the dictionary named Dic_employees2 contains two key-value pairs. The content Dic_employees2 will be added at the end of the Dic_emplyees1 after executing the update() function because no matching key exists between the dictionaries. The original and the modified dictionary will be printed in the output.

# Declare the first dictionary
Dic_employees1 = {'56': 'Md. Hanif', '84': 'Neha Ali', '59': 'Mizanur Rahman'}
# Declare the second dictionary
Dic_employees2 = {'78': 'Kamal Hasan', '42': 'Zinia Rahman'}

# The content of the first Dictionary before modification
print("The values of the first Dictionary before using update():")
print(Dic_employees1)
'''
Add the content of the second dictionary
at the end of the first dictionary
using update() method
'''

Dic_employees1.update(Dic_employees2)
print("\nThe values of the first Dictionary after using update():")
print(Dic_employees1)

Output:

The following output will appear after executing the above script.

Example-2: Update dictionary with the iterable object

Create a python file with the following script to update the content of a dictionary with two iterable objects. A dictionary named employees have been declared in the script with three key-value pairs. Next, two iterable objects have been used as the arguments of the update() function where the object named A3 matches with one key of the dictionary. In this case, the matching key of the dictionary will be updated by the value of the matching iterable object, and another iterable object will be inserted into the dictionary.

# Declare the first dictionary
employees = {'A1': 'Md. Hanif', 'A2': 'Neha Ali', 'A3': 'Mizanur Rahman'}

# The content of the dictionary before modification
print("The values of the dictionary before using update()")
print(employees)

# Update the dictionary with the iterable
employees.update(A3='Nirob Hasan', A4='JakiaAkter')
print("\nThe values of the dictionary after using update():")
print(employees)

Output:

The following output will appear after executing the above script. In the output, the value of the A3 key of the dictionary has been updated by the value of the A3 object.

Example-3: Checking the key of the dictionary before the update

In the previous example, the value of the original dictionary has been changed by the value of another dictionary if the same key exists in both dictionaries. This situation can be prevented by checking the key before updating the dictionary. Create a python file with the following script that will check the key of the second dictionary before inserting or updating that key-value to the first dictionary. If the key of the first dictionary matches with the key of the second dictionary, then the value of that key will not be changed; otherwise, the key-value pair of the second dictionary will be added to the first dictionary.

# Declare the first dictionary
dic_employees1 = {'01': 'Md. Hanif', '02': 'Neha Ali'}
# Declare the second dictionary
dic_employees2 = {'02': 'Kamal Hasan', '03': 'Zinia Rahman',  '04': 'Mizanur Rahman'}

# The content of the dictionary before modification
print("The values of the dictionary before using update():")
print(dic_employees1)

for key, value in dic_employees2.items():
if key in dic_employees1.keys():
print(key)
continue
dic_employees1.update({key: value})

print("\nThe values of the dictionary after using update():")
print(dic_employees1)

Output:

The following output will appear after executing the above script. In the output, the value of the ’02’ key of the first dictionary didn’t change by the value of the ’02’ key of the second dictionary.

Example-4: Update dictionary by list values

Create a python file with the following script for updating a dictionary by using a list of tuples and the list of another list. The dictionary named employees contains two key-value pairs. Next, a list of two tuples of two elements has been used as the argument of the update() function. The first element has been used as the key, and the second element has been used as the value of each tuple when updating the dictionary. The values of the nested list will be added to the dictionary in the same way.

# Declare the first dictionary
employees = {'01': 'Md. Hanif', '02': 'Neha Ali'}
# The content of the dictionary before modification
print("The values of the dictionary before using update():")
print(employees)

# Update the dictionary with a list of tuples
employees.update([('03', 'MehrNigar'), ('04', 'Zafar Ali')])
# The content of the dictionary before modification
print("The values of the dictionary after adding tuple values:")
print(employees)

# Update the dictionary with a nested list
employees.update([['05', 'Bela Chowdhury'], ['06', 'Joly Akter']])
# The content of the dictionary before modification
print("The values of the dictionary after adding list values:")
print(employees)

Output:

The following output will appear after executing the above script. The updated dictionary contains 6 elements in the output after adding 2 tuples and 2 lists.

Conclusion:

A dictionary can be updated by another dictionary or any iterable object such as a list or tuple. Different ways of updating a dictionary by using the update() function have been shown in this tutorial by using simple python examples to help the new python users.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.