Use the update() function to update a dictionary in Python. Using this method you can insert the specified items, dictionary, or iterable object with key-value pairs into the dictionary.
dictionary.update(iterable)
Example update Python dictionary
A simple example code inserts an item into the dictionary:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.update({"color": "Red"})
print(car)
Output:
Or Directly assigning new key-value pairs:
my_dict = {'a': 1, 'b': 2}
my_dict['c'] = 3
my_dict['d'] = 4
print(my_dict)
Update() using Tuple
d = {'x': 2}
d.update(y=3, z=0)
print(d)
Output: {‘x’: 2, ‘y’: 3, ‘z’: 0}
Update with another Dictionary
d1 = {'A': 0, 'B': 1, }
d2 = {'B': 2}
d1.update(d2)
print(d1)
Output: {‘A’: 0, ‘B’: 2}
Comment if you have any doubts or suggestions on this Python dictionary topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.