Python dictionary update() Method



The Python dictionary update() method is used to update the key-value pairs of a dictionary. These key-value pairs are updated from another dictionary or iterable like tuple having key-value pairs.

If the key value pair is already present in the dictionary, then the existing key is changed with the new value using update() method. On the other hand if the key-value pair is not present in the dictionary, then this method inserts it.

Syntax

Following is the syntax of Python dictionary update() method −

dict.update(other)

Parameters

  • other − This is the dictionary to be added into dict.

Return Value

This method does not return any value.

Example

The following example shows the usage of Python dictionary update() method. Here a dictionary 'dict' is created which consists the values: 'Zara' and '7' against the keys 'Name' and 'Age'. Then another dictionary 'dict2' is created which consist of the key 'Sex' and its corresponding value 'female'. Thereafter, using the update() method 'dict' gets updated with the items provided in 'dict2'.

# Creating the first dictionary
dict = {'Name': 'Zara', 'Age': 7}
# Aanother dictionary
dict2 = {'Sex': 'female' }
# using the update() method
dict.update(dict2)
print ("Value : %s" %  dict)

When we run above program, it produces following result −

Value : {'Name': 'Zara', 'Age': 7, 'Sex': 'female'}

Example

In the code below, a list of tuples is passed as an argument to the update() method. Here, the first element of the tuple acts as a key and the second element acts as a value.

# creating a dictionary
dict_1 = {'Animal': 'Lion'}
# updating the dictionary
res = dict_1.update([('Kingdom', 'Animalia'), ('Order', 'Carnivora')])
print('The updated dictionary is: ',dict_1)

While executing the above code we get the following output −

The updated dictionary is:  {'Animal': 'Lion', 'Kingdom': 'Animalia', 'Order': 'Carnivora'}

Example

In here, the existing key 'RollNo' is updated using the update() method. This key is already present in the dictionary. Hence, it gets updated with a new key-value pair.

dict_1 = {'Name': 'Rahul', 'Hobby':'Singing', 'RollNo':34}
# updating the existing key
res = dict_1.update({'RollNo':45})
print('The updated dictionary is: ',dict_1)

Following is an output of the above code −

The updated dictionary is:  {'Name': 'Rahul', 'Hobby': 'Singing', 'RollNo': 45}

Example

In the example given below the key:value pair is specified as keyword arguments. When a method is invoked, the keyword(name) of the argument is used to assign value to it.

# creating a dictionary
dict_1 = {'Animal': 'Lion'}
res = dict_1.update(Order = 'Carnivora', Kingdom = 'Animalia')
print(dict_1)

Output of the above code is as follows −

{'Animal': 'Lion', 'Order': 'Carnivora', 'Kingdom': 'Animalia'}
python_dictionary.htm
Advertisements