KnowledgeBoat Logo

Computer Science

Dictionary is a mutable type, which means you can modify its contents ? What all is modifiable in a dictionary ? Can you modify the keys of a dictionary ?

Python Dictionaries

4 Likes

Answer

Yes, we can modify the contents of a dictionary.
Values of key-value pairs are modifiable in dictionary. New key-value pairs can also be added to an existing dictionary and existing key-value pairs can be removed.
However, the keys of the dictionary cannot be changed. Instead we can add a new key : value pair with the desired key and delete the previous one.
For example:

d = { 1 : 1 }
d[2] = 2   
print(d)
d[1] = 3   
print(d)
d[3] = 2
print(d)
del d[2]
print(d)
Output
{1: 1, 2: 2}  
{1: 3, 2: 2} 
{1: 3, 2: 2, 3: 2}  
{1: 3, 3: 2} 
Explanation

d is a dictionary which contains one key-value pair.
d[2] = 2 adds new key-value pair to d.
d[1] = 3 modifies value of key 1 from 1 to 3.
d[3] = 2 adds new key-value pair to d.
del d[2] deletes the key 2 and its corresponding value.

Answered By

2 Likes


Related Questions