Python Dictionary update() Method

The dict.update() method updates the dictionary with the key-value pairs from another dictionary or another iterable such as tuple having key-value pairs.

Syntax:

dict.update(iterable)

Parameters:

iterable: (optional) A dictionary or an iterable with key,value pairs.

Return Value:

None.

The following updates the dictionary using the dict.update() method.

Example:
romanNums = {'I':1,'III':3,'V':5}
print("Dictionary: ",romanNums)

evenRomanNums = {'II':2,'IV':4}
romanNums.update(evenRomanNums)
print("Updated Dictionary: ",romanNums)
Output
Dictionary:  {'I': 1, 'III': 3, 'V': 5}
Updated Dictionary:  {'I': 1, 'III': 3, 'V': 5, 'II': 2, 'IV': 4}

A tuple can also be passed in the update() method to update the dictionary.

Example: Add Tuple Element to Dictionary
romanNums = {'I':1,'III':3,'V':5}
print("Dictionary: ",romanNums)

romanNums.update((II=2,IV=4))
print("Updated Dictionary: ",romanNums)
Output
Dictionary:  {'I': 1, 'III': 3, 'V': 5}
Updated Dictionary:  {'I': 1, 'III': 3, 'V': 5, 'II': 2, 'IV': 4}

If no argument is passed, the dictionary remains unchanged.

Example: update()
romanNums = {'I':1,'III':3,'V':5}
print("Dictionary: ",romanNums)

romanNums.update()
print("Updated Dictionary: ",romanNums)
Output
Dictionary:  {'I': 1, 'II': 2 }
Updated Dictionary:  {'I': 1, 'II': 2 }