Last Updated on May 28, 2024 by Roshan Parihar
To add multiple items to Dictionary in Python, use the update()
function and pass the item with a key-value pair to update.
You can also use the update() function to update the old value of the existing key of the Dictionary with the new value. Let’s find out with the examples.
Add Multiple Items To Dictionary Using update() Function in Python
If you want to add multiple items to the Dictionary, you have to use the update()
function. Just pass the multiple key-value pairs in comma-separation to add or append to Dictionary. It gets appended to the end of the dictionary elements.
Example 1
1 2 3 |
myDict = {'one': 'Sally', 'two': 13, 'three': 'Dingra', 'four': 'Lilop'}; myDict.update({'five':'Olive','six':'Nivo','seven':'Xavier'}); print(myDict); |
Output
The above example previously contained only the 4 items with the keys and associated element values. However, after using the update function, the function appends multiple values to the dictionary and shows 7 elements that you can check in the above example.
Update Single Item to Dictionary in Python
By using the update()
function in Python, you can update a single item value according to the mentioned key of Dictionary. To change the old value with the new one, you have to specify the new value for the key as given below.
Example 2
1 2 3 |
myDict = {'one': 'Sally', 'two': 13, 'three': 'Dingra', 'four': 'Lilop'}; myDict.update({'two':'Billy'}); print(myDict); |
Output
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 the below methods.
Update Multiple Elements in Python
In addition to adding the new multiple items, you can also update or change the multiple existing key associated elements using the same update()
function.
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.
Example 3
1 2 3 |
myDict = {'one': 'Sally', 'two': 13, 'three': 'Dingra', 'four': 'Lilop'}; myDict.update({'two':'Kelly','three':'Rancho','four':'Guru'}); print(myDict); |
Output
The above example shows 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.
DOWNLOAD Free PYTHON CHEAT SHEET
You may also like to read