In Python, you can use the update()
method to update a dictionary with key-value pairs from another dictionary or an iterable of key-value pairs. The syntax for using the update()
method is as follows:
my_dict.update(other_dict)
or
my_dict.update(iterable)
Here, my_dict
is the name of the dictionary that you want to update, other_dict
is the dictionary from which you want to add key-value pairs, and iterable
is an iterable of key-value pairs (e.g. a list of tuples).
When you call the update()
method, any key-value pairs in other_dict
or iterable
that have keys that already exist in my_dict
will overwrite the existing values. Any key-value pairs in other_dict
or iterable
that have keys that do not exist in my_dict
will be added to my_dict
.
Here’s an example:
# Define a dictionary
my_dict = {"apple": 2, "banana": 3, "orange": 4}
# Print the original dictionary
print("Original dictionary:", my_dict)
# Update the dictionary with key-value pairs from another dictionary
other_dict = {"banana": 5, "grape": 6}
my_dict.update(other_dict)
# Print the modified dictionary
print("Modified dictionary:", my_dict)
# Update the dictionary with key-value pairs from an iterable
iterable = [("kiwi", 2), ("banana", 7)]
my_dict.update(iterable)
# Print the modified dictionary again
print("Modified dictionary:", my_dict)
Output
Original dictionary: {'apple': 2, 'banana': 3, 'orange': 4}
Modified dictionary: {'apple': 2, 'banana': 5, 'orange': 4, 'grape': 6}
Modified dictionary: {'apple': 2, 'banana': 7, 'orange': 4, 'grape': 6, 'kiwi': 2}
Note that if you try to update a dictionary with an iterable that contains duplicate keys, only the last value for each key will be included in the resulting dictionary. This is because each key in a dictionary must be unique.