![]() |
In this article, we will learn what are the different ways to add values in a dictionary in Python. Assign values using unique keysAfter defining a dictionary we can index through it using a key and assign a value to it to make a key-value pair. Python3
Output:
But what if a key already exists in it? Python3
Output:
We can observe that the value corresponding to key 0 has been updated to ‘Tomato’ from ‘Carrot’. Merging two dictionaries using update()We can merge two dictionaries by using the update() function. Python3
Output:
Add values to dictionary Using two lists of the same lengthThis method is used if we have two lists and we want to convert them into a dictionary with one being key and the other one as corresponding values. Python3
Output:
Converting a list to the dictionaryThis method is used to convert a python list into a python dictionary with indexes as keys. Python3
Output:
There are other methods as well to add values to a dictionary but the above-shown methods are some of the most commonly used ones and highly efficient as well. Add values to dictionary Using the merge( | ) operatorBy using the merge operator we can combine two dictionaries. Python3
Output:
Add values to dictionary Using the in-place merge( |= ) operator.By using the in place merge operator we can combine two dictionaries. In in place operator, all elements of one dictionary are added in the other but while using merge original state of the dictionaries remains the same and a new one is created. Python3
Output:
Note: Methods 4 and 5 work in only Python 3.9+ versions. |
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |