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

Similar Reads

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....

Merging two dictionaries using update()

...

Add values to dictionary Using two lists of the same length

...

Converting a list to the dictionary

We can merge two dictionaries by using the update() function....

Add values to dictionary Using the merge( | ) operator

...

Add values to dictionary Using the in-place merge( |= ) operator.

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....

Contact Us