Last Updated on May 20, 2024 by Roshan Parihar
To add a new key-value pair in Dictionary using Python, use the Python update()
function and place new items.
You can add single elements as well as multiple items to the Dictionary with this. Each new element comes with a new key-value pair. let’s see some examples of it.
Add New Key Value Pair in Dictionary Using Update() in Python
If you want to add a new key-value pair, you can use the update()
function and pass the element as the argument. The passed argument should contain the key and value enclosed within the curly({}) brackets inside the function.
On execution of the code, it adds a new item to the end of the Dictionary.
Example 1
1 2 3 |
myDict = {'one': 'Ram', 'two': 13, 'three': 'Jordge', 'four': 'Gill'} myDict.update({'six': 'Billy'}) print(myDict) |
Output
The above example contains the newly added element to the end. The newly appended element is with key ‘six’ and its associated value is ‘Billy’.
This is all about adding a single element to the Dictionary. However, you can also add multiple items together to the Dictionary using the same function. Read the below section to perform this task.
Assigning New Values in Python
You have to use the new key and assign the new value to it. The below example performs the addition of the new element to the end of the Dictionary items.
Example 2
1 2 3 |
myDict = {'one': 'Ram', 'two': 13, 'three': 'Jordge', 'four': 'Gill'} myDict['five'] = 33 print(myDict) |
Output
The above example contains the newly added element at the end of the Dictionary. The new element key is ‘five’ and its associated value is 33.
However, the above example is not the only method you can use. You can also add the new element using the Python update function. Read further to see the method of using this function.
Multiple Key-Value Pair Addition in Dictionary
In addition to the above, you can add also add multiple elements to the Dictionary using the update()
. To add multiple elements, you have to pass multiple items as the argument of the update function.
The argument with multiple elements should be enclosed within the curly({}) brackets. See the example below to add multiple items to your Dictionary in Python.
Example 3
1 2 3 |
myDict = {'one': 'Ram', 'two': 13, 'three': 'Jordge', 'four': 'Gill'} myDict.update({'seven': 'Kelly', 'eight': 'Brock'}) print(myDict) |
Output
The above example contains the two newly added elements to the Dictionary. However, you can add more elements together using the update function. You just have to put more elements as the argument of the function.