Python Dictionary update() Method

Updates/Adds multiple items to the dictionary


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).



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


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

Example: Merge two dictionaries

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

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

Example: Merge two dictionaries having common key

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

Note that the value for 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).

Example: Passing a dictionary object

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

Example: Passing a list of tuples

D = {'name': 'Bob'}
D.update([('job', 'Dev'), ('age', 25)])
print(D)    # {'age': 25, 'job': 'Dev', 'name': 'Bob'}

Example: Passing an iterable of length two (nested list)

D = {'name': 'Bob'}
D.update([['job', 'Dev'], ['age', 25]])
print(D)    # {'age': 25, 'job': 'Dev', 'name': 'Bob'}

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

Example: Specifying key:value pairs as keyword arguments

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