Dictionary update() Method in Python

Python Dictionary update() Method

The update() method in Python dictionaries is used to update or merge the contents of one dictionary with another dictionary or with an iterable of key-value pairs. It modifies the dictionary in-place by adding new key-value pairs from the provided dictionary or iterable, or updating the values of existing keys if they already exist in the dictionary.

Syntax of the update() method:

dictionary.update(other_dictionary)

or

dictionary.update(iterable)
  • other_dictionary: It is another dictionary whose key-value pairs will be added or updated in the original dictionary.
  • iterable: It can be any iterable that contains key-value pairs, where each pair is represented as a tuple (key, value).

Now, let's see some examples of how to use the update() method:

Example 1: Updating a dictionary with another dictionary

# Original dictionary
fruit_colors = {'apple': 'red', 'banana': 'yellow'}

# Dictionary to be merged with the original dictionary
more_fruits = {'orange': 'orange', 'grapes': 'purple'}

# Update the original dictionary with the key-value pairs from 'more_fruits'
fruit_colors.update(more_fruits)

# Print the updated dictionary
print(fruit_colors)

Output:

{'apple': 'red', 'banana': 'yellow', 'orange': 'orange', 'grapes': 'purple'}

In this example, the update() method is used to update the fruit_colors dictionary with the key-value pairs from the more_fruits dictionary. As a result, the fruit_colors dictionary now contains all the key-value pairs from both dictionaries.

Example 2: Updating a dictionary with an iterable of key-value pairs

# Original dictionary
fruit_colors = {'apple': 'red', 'banana': 'yellow'}

# Iterable of key-value pairs to be merged with the original dictionary
new_fruits = [('orange', 'orange'), ('grapes', 'purple')]

# Update the original dictionary with the key-value pairs from 'new_fruits'
fruit_colors.update(new_fruits)

# Print the updated dictionary
print(fruit_colors)

Output:

{'apple': 'red', 'banana': 'yellow', 'orange': 'orange', 'grapes': 'purple'}

In this example, the update() method is used to update the fruit_colors dictionary with the key-value pairs from the new_fruits iterable. As a result, the fruit_colors dictionary now contains all the key-value pairs from both the original dictionary and the iterable.

It's important to note that if the keys already exist in the original dictionary, the update() method will update their values with the new values provided in the other dictionary or iterable. If the keys are not found in the original dictionary, new key-value pairs will be added to it.

The update() method is a convenient way to add or modify multiple key-value pairs in a dictionary in one operation.