CBSE Class 12 Computer Science
Question 69 of 105
Python Revision Tour II — Question 18
Back to all questionsYes, 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){1: 1, 2: 2}
{1: 3, 2: 2}
{1: 3, 2: 2, 3: 2}
{1: 3, 3: 2}
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.