Understand Python Dictionary update(): Update or Append Key Value with Another Dictionary

By | May 9, 2020

Python dictionary update() method can allow us to update a dict with another dictionary. In this tutorial, we will use some examples to illustrate python beginners how to use it.

Syntax

dict.update(dict2)

Update or append key value from dict2 into dict, which means this function will return None and dict will be changed by dict2.

For example:

dict_1 = {'site_name': 'Tutorial Example'}

dict_2 = {'site_url': 'https://www.tutorialexample.com'}

dict_1.update(dict_2)

print(dict_1)

Run this code, you will find dict_1 will be:

{'site_name': 'Tutorial Example', 'site_url': 'https://www.tutorialexample.com'}

In this code, we will append key:value in dict_2 into dict_1.

However, how about there are some same keys in dict_1 and key_2?

Same key in dict_1 and dict_2

Here is an example.

dict_1 = {'site_name': 'Tutorial Example'}

dict_2 = {'site_name': 'tutorialexample.com'}

dict_1.update(dict_2)

print(dict_1)

In this code, key site_name is in both dict_1 and dict_2. dict_1.update(dict_2) will replace the value of key site_name using dict_2.

Run this code, you will get this result.

{'site_name': 'tutorialexample.com'}

dict_2 is empty

If dict_2 is empty, dict_1 will be not changed. Here is an example.

dict_1 = {'site_name': 'Tutorial Example'}

dict_2 = {}

dict_1.update(dict_2)

print(dict_1)

Run this code, you will find dict_1 is:

{'site_name': 'Tutorial Example'}

Leave a Reply