Python Dictionary update() Method

Updates/Adds multiple items to the dictionary

Usage

The update() method updates the dictionary with the key:value pairs from element.

  • If the key is already present in the dictionary, value gets updated.
  • If the key is not present in the dictionary, a new key:value pair is added to the dictionary.

element can be either another dictionary object or an iterable of key:value pairs (like list of tuples).

Syntax

dictionary.update(element)

Python dictionary update() method parameters
ParameterConditionDescription
elementOptionalA dictionary or an iterable of key:value pairs

Examples

update() method is generally used to merge two dictionaries.

D1 = {'name': 'Bob'}
D2 = {'job': 'Dev', 'age': 25}
D1.update(D2)
print(D1)
# Prints {'job': 'Dev', 'age': 25, 'name': 'Bob'}

When two dictionaries are merged together, existing keys are updated and new key:value pairs are added.

D1 = {'name': 'Bob', 'age': 25}
D2 = {'job': 'Dev', 'age': 30}
D1.update(D2)
print(D1)
# Prints {'job': 'Dev', 'age': 30, 'name': 'Bob'}

Note that the value for existing key ‘age’ is updated and new entry ‘job’ is added.

Passing Different Arguments

update() method accepts either another dictionary object or an iterable of key:value pairs (like tuples or other iterables of length two).

# Passing a dictionary object
D = {'name': 'Bob'}
D.update({'job': 'Dev', 'age': 25})
print(D)
# Prints {'job': 'Dev', 'age': 25, 'name': 'Bob'}
# Passing a list of tuples
D = {'name': 'Bob'}
D.update([('job', 'Dev'), ('age', 25)])
print(D)
# Prints {'age': 25, 'job': 'Dev', 'name': 'Bob'}
# Passing an iterable of length two (nested list)
D = {'name': 'Bob'}
D.update([['job', 'Dev'], ['age', 25]])
print(D)
# Prints {'age': 25, 'job': 'Dev', 'name': 'Bob'}

key:value pairs can be also be specified as keyword arguments.

# Specifying key:value pairs as keyword arguments
D = {'name': 'Bob'}
D.update(job = 'Dev', age = 25)
print(D)
# Prints {'job': 'Dev', 'age': 25, 'name': 'Bob'}