Python Dictionary update
Now, we are going to learn about the update method, in relation to the dictionary. With the update method, we can insert the specified item into the dictionary. These specified items can be a dictionary or some iterable object with key-value pairs.
Let’s have a look at an example, where we would try to insert the key-value pairs from another dictionary into our dictionary.
Python Dictionary update() Method
In the above program, we have two dictionaries, with reference variables, sample_dict, and another_dict. What we wish to do, is insert the elements from another dictionary into the sample dictionary. We can do this with the update method.
Since we want to add the elements FROM another dictionary TO the sample dictionary, we are calling the update method with the sample dictionary, and then passing another dictionary as an argument to the update method. Doing this, the elements from another dictionary would be added to the sample dictionary.
If we try to run the above program, the output that we get is something like this –
C:\Users\GyaniPandit\Desktop\python> python dictionary.py
{‘one’: 1, ‘two’: 2, ‘three’: 3, ‘four’: 4, ‘five’: 5}
As you can see, the sample_dict has the elements from the another_dict. So, if you want to insert the elements from some dictionary into another dictionary, you can make use of the update method.
Other than another dictionary, we can also pass some other iterable. Let’s have a look at another program, which demonstrates the same thing.
As you can see in the above program, we have a list of tuples. These can be considered as the key-value pairs here. You can simply try to execute the above program yourselves and try to observe the output of the above program. So, as and when required, we can make use of the update method in our program. Note that the update method adds the element in the dictionary if the key is not there in the dictionary. If the key is there in the dictionary, the key is updated with the new value.