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’.
How to add values to dictionary in Python
In this article, we will learn what are the different ways to add values in a dictionary in Python.
Contact Us