Skip to main content

Python Dictionary update() Function

The Dictionary update() method is used to update the dictionary with the elements from another dictionary object or from an iterable of key-value pairs.

Syntax

my_dictionary.update(element)

update() Parameters

Python Dictionary update() method parameters:

ParameterConditionDescription
elementOptionalA dictionary or an iterable of key:value pairs
note

If update() method is called without passing parameters, the dictionary remains unchanged.

update() Return Value

Python Dictionary update() function does not return any value (returns None), but it modifies the dictionary in place.

Examples

Example 1: Basic Usage of update() method in dictionary

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

my_dict1 = {'name': 'Tom'}
my_dict2 = {'job': 'Developer', 'age': 25}
my_dict1.update(my_dict2)

print(my_dict1) # Output: {'job': 'Dev', 'age': 25, 'name': 'Bob'}

output

{'name': 'Tom', 'job': 'Developer', 'age': 25}

When two dictionaries are merged together, existing keys are updated and new key-value pairs are added. For example, note that the value for existing key age is updated and new entry job is added.

my_dict1 = {'name': 'Tom', 'age': 25}
my_dict2 = {'job': 'Developer', 'age': 30}
my_dict1.update(my_dict2)

print(my_dict1) # Output: {'name': 'Tom', 'age': 30, 'job': 'Developer'}

output

{'name': 'Tom', 'age': 30, 'job': 'Developer'}

Example : update() with an Iterable of length two (nested list)

The update() method accepts an iterable of key-value pairs (iterables of length two, like nested lists).

For example, let's pass an iterable of length two (nested list)

my_dict = {'name': 'Tom'}
my_dict.update([['job', 'Developer'], ['age', 25]])

print(my_dict) # Output: {'name': 'Tom', 'job': 'Developer', 'age': 25}

output

{'name': 'Tom', 'job': 'Developer', 'age': 25}

Example : update() with List of Tuples

The update() method accepts a list of tuples.

For example:

my_dict = {'name': 'Tom'}
my_dict.update([('job', 'Developer'), ('age', 25)])

print(my_dict) # Output: {'name': 'Tom', 'job': 'Developer', 'age': 25}

output

{'name': 'Tom', 'job': 'Developer', 'age': 25}

Example : update() with Keyword Arguments

The update() method accepts also key-value pairs as keyword arguments.

For example, let's specify key-value pairs as keyword arguments

my_dict = {'name': 'Tom'}
my_dict.update(job = 'Developer', age = 25)

print(my_dict) # Output: {'name': 'Tom', 'job': 'Developer', 'age': 25}

output

{'name': 'Tom', 'job': 'Developer', 'age': 25}