How to Use the Python Dictionary update() Method

09/16/2021

Contents

In this article, you will learn how to use the Python dictionary update() method.

Python Dictionary update() Method

The update() method in Python is used to merge one dictionary with another. It takes another dictionary or an iterable of key-value pairs as its argument and updates the calling dictionary with those key-value pairs.

Syntax

Here’s the syntax of the update() method:

dict.update([other])
Parameters
  • dict: The dictionary that you want to update.
  • other: Either another dictionary or an iterable of key-value pairs.
Example

Here are some examples of how to use the update() method:

Updating a dictionary with another dictionary
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict1.update(dict2)
print(dict1) # Output: {'a': 1, 'b': 3, 'c': 4}

In the above example, dict1 is updated with the key-value pairs from dict2. Since dict2 has a key ‘b’ which is already present in dict1, its value gets updated to 3.

Updating a dictionary with an iterable of key-value pairs
dict1 = {'a': 1, 'b': 2}
iterable = [('b', 3), ('c', 4)]
dict1.update(iterable)
print(dict1) # Output: {'a': 1, 'b': 3, 'c': 4}

In the above example, an iterable of key-value pairs is passed to the update() method, which updates dict1 with those key-value pairs.

Updating a dictionary with keyword arguments
dict1 = {'a': 1, 'b': 2}
dict1.update(c=3, d=4)
print(dict1) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}

In the above example, keyword arguments are passed to the update() method, which updates dict1 with those key-value pairs.

Note: When there are common keys between the two dictionaries, the update() method updates the values of the calling dictionary with the values of the other dictionary.