Python dictionary update | Example code

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

Simple example code insert an item to the dictionary:

car = {
    "brand": "Ford",
    "model": "Mustang",
    "year": 1964
}

car.update({"color": "Red"})

print(car)

Output:

Python dictionary update

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}

Do comment if you have any doubts or suggestions on this Python dictionary topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.