AppDividend
Latest Code Tutorials

Python Dictionary update() Function Example

0

Python dictionary update() is an inbuilt method that updates one dictionary with the elements of another dictionary object or from an iterable value of key pair. If a key is not present in the dictionary, it first adds the key to the dictionary. After that, it combines the value; otherwise, if the key is already present in the dictionary, it just updates the value.

Python Dictionary update()

Python dict update() method updates the dictionary with the elements from another dictionary object or an iterable of key/value pairs. Dict update() method adds element(s) to a dictionary if the key is not in the dictionary. If the key is in a dictionary, it updates the key with a new value.

Syntax

dict1.update(dict2)

Here dict1 is the dictionary in which we want to update, and dict2 is the dictionary from which we want to copy.

Return Value

The dict update() method does not return anything, and it just updates one dictionary with other dictionary objects or iterable key/pairs.

Programming Example

# app.py

# Declaring two dictionaries
dict1 = {'Flower': 'Rose', 'Fruit': 'Apple', 'Bird': 'Parrot'}
dict2 = {'Animal': 'Tiger', 'Tree': 'Coconut'}

# Printing dictionary1 and Dictionary2
print(dict1)
print(dict2)

# Now we will update dict1 with the value of dict2
dict1.update(dict2)

# Now printing new values of dictionary1
print(dict1)

Output

{'Flower': 'Rose', 'Fruit': 'Apple', 'Bird': 'Parrot'}
{'Animal': 'Tiger', 'Tree': 'Coconut'}
{'Flower': 'Rose', 'Fruit': 'Apple', 'Bird': 'Parrot', 'Animal': 'Tiger', 'Tree': 'Coconut'}

In the above program, we have declared two dictionary dict1 and dict2. Then we have printed all the keys and values of the dictionaries. Then we have updated dict1 with the objects of dict2, and finally, we have printed them.

Update dictionary with an iterable in Python

Let’s update the dictionary with an iterable in Python.

# app.py

Dictionary1 = {'K':'Krunal'}

# Dictionary before Updation
print("Original Dictionary:")
print(Dictionary1)

# update the Dictionary with iterable
Dictionary1.update(A ='Ankit', R = 'Rushabh')
print("Dictionary after updation:")
print(Dictionary1)

Output

➜  pyt python3 app.py
Original Dictionary:
{'K': 'Krunal'}
Dictionary after updation:
{'K': 'Krunal', 'A': 'Ankit', 'R': 'Rushabh'}

Conclusion

Python Dictionary update() method updates the dictionary with the elements from another dictionary object or an iterable of key/value pairs.

See also

Python dictionary setDefault()

Python dictionary popitem()

Python dictionary items()

Python dictionary fromKeys()

Python dictionary keys()

Leave A Reply

Your email address will not be published.

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