How to add values to dictionary in Python
Last Updated :
27 Jul, 2023
In this article, we will learn what are the different ways to add values in a dictionary in Python.
Assign values using unique keys
After defining a dictionary we can index through it using a key and assign a value to it to make a key-value pair.
Python3
veg_dict = {}
veg_dict[ 0 ] = 'Carrot'
veg_dict[ 1 ] = 'Raddish'
veg_dict[ 2 ] = 'Brinjal'
veg_dict[ 3 ] = 'Potato'
print (veg_dict)
|
Output:
{0: ‘Carrot’, 1: ‘Raddish’, 2: ‘Brinjal’, 3: ‘Potato’}
But what if a key already exists in it?
Python3
veg_dict[ 0 ] = 'Tomato'
print (veg_dict)
|
Output:
{0: ‘Tomato’, 1: ‘Raddish’, 2: ‘Brinjal’, 3: ‘Potato’}
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
veg_dict = { 0 : 'Carrot' , 1 : 'Raddish' ,
2 : 'Brinjal' , 3 : 'Potato' }
veg_dict.update({ 4 : 'Tomato' , 5 : 'Spinach' })
print (veg_dict)
|
Output:
{0: ‘Carrot’, 1: ‘Raddish’, 2: ‘Brinjal’, 3: ‘Potato’, 4: ‘Tomato’, 5: ‘Spinach’}
Add values to dictionary Using two lists of the same length
This 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
roll_no = [ 10 , 20 , 30 , 40 , 50 ]
names = [ 'Ramesh' , 'Mahesh' , 'Kamlesh' ,
'Suresh' , 'Dinesh' ]
students = dict ( zip (roll_no, names))
print (students)
|
Output:
{10: ‘Ramesh’, 20: ‘Mahesh’, 30: ‘Kamlesh’, 40: ‘Suresh’, 50: ‘Dinesh’}
Converting a list to the dictionary
This method is used to convert a python list into a python dictionary with indexes as keys.
Python3
vegetables = [ 'Carrot' , 'Raddish' ,
'Brinjal' , 'Potato' ]
veg_dict = dict ( enumerate (vegetables))
print (veg_dict)
|
Output:
{0: ‘Carrot’, 1: ‘Raddish’, 2: ‘Brinjal’, 3: ‘Potato’}
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( | ) operator
By using the merge operator we can combine two dictionaries.
Python3
veg1 = { 0 : 'Carrot' , 1 : 'Raddish' }
veg2 = { 2 : 'Brinjal' , 3 : 'Potato' }
veg_dict = (veg1 | veg2)
print (veg_dict)
|
Output:
{0: ‘Carrot’, 1: ‘Raddish’, 2: ‘Brinjal’, 3: ‘Potato’}
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
veg1 = { 0 : 'Carrot' , 1 : 'Raddish' }
veg2 = { 2 : 'Brinjal' , 3 : 'Potato' }
veg1 | = veg2
print (veg1)
|
Output:
{0: ‘Carrot’, 1: ‘Raddish’, 2: ‘Brinjal’, 3: ‘Potato’}
Note: Methods 4 and 5 work in only Python 3.9+ versions.
Please Login to comment...