CBSE Class 11 Computer Science Question 82 of 112

Dictionaries — Question 4

Back to all questions
4
Question

Question 4

Nesting of dictionary allows you to store a dictionary inside another dictionary. Then why is following code raising error ? What can you do to correct it ?

d1 = {1 : 10, 2 : 20, 3 : 30}
d2 = {1 : 40, 2 : 50, 3 : 60}
d3 = {1 : 70, 2 : 80, 3 : 90}
d4 = {d1 : "a", d2 : "b", d3 : "c"}
Answer

Dictionaries can be stored inside another dictionary as values and not as keys. Here, d4 is storing the other dictionaries as keys which is not allowed because dictionaries are mutable objects. That's why this code is raising error.
It can be corrected by using d1, d2, d3 as values of d4.
The corrected code is shown below:

d4 = { "a": d1, "b": d2, "c": d3}