In this tutorial, learn how to add or update the multiple items to Dictionary using Python. The short answer is: use the update() function of Python to Add single or multiple elements to the Dictionary.

You can also use the update() to change or replace the old value of the existing keys of Dictionary. You may also like to read Add Element To Key In Dictionary Using Python.

If the key is new, it gets added to them with the new value. While, if the key is old but its value is new, it replaces the old value of the key with the new one.

Append or Change Single Element of Dictionary With Python

By using the update() function of Python, you can add or change the single key value of Dictionary. To change the old value with the new one, you have to use the below-given method.

Output

{‘one’: ‘Sally’, ‘two’: ‘Billy’, ‘three’: ‘Dingra’, ‘four’: ‘Lilop’}

The above example contains the 4 elements including the keys and the associated values. The output contains the changed new value associated with the key ‘two’.

You can change only the single value using the above example. However, you can also add multiple keys and values in one go by using below methods.

Add Multiple Items To Dictionary in Python

To add the new multiple items to the Dictionary in one go. You have to use the update() function and add all the items together in the function. These multiple items get appended to the end of the myDict variable in Python.

Output

{‘one’: ‘Sally’, ‘two’: 13, ‘three’: ‘Dingra’, ‘four’: ‘Lilop’, ‘five’: ‘Olive’, ‘six’: ‘Nivo’, ‘seven’: ‘Xavier’}

The above example previously contains only the 4 items with the keys and associated elements. However, after using the update function, Its showing 7 elements you can check in the above example.

Update Multiple Elements Using Python

In addition to adding the new multiple items, you can also update or change the multiple existing keys associated elements.

If the key value is new, it gets replaced by the old value. However, if the value is not new, the value associated with the key remains the same.

Output

{‘one’: ‘Sally’, ‘two’: ‘Kelly’, ‘three’: ‘Rancho’, ‘four’: ‘Guru’}

The above example showing the changed value for the keys ‘two’, ‘three’ and ‘four’. You can change or replace multiple numbers of items as per your requirement. You just have to provide the new value in the update function using Python.

You may also like to read

Hope, you like this post of how to update multiple items of Dictionary in Python. If you have any query regarding the tutorial, please comment below.

Also tell me, which method you are using for updating the Dictionary using Python

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.