Computer Science
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"}
Python Dictionaries
18 Likes
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}
Answered By
11 Likes
Related Questions
The following code is giving some error. Find out the error and correct it.
d1 = {"a" : 1, 1 : "a", [1, "a"] : "two"}The following code has two dictionaries with tuples as keys. While one of these dictionaries being successfully created, the other is giving some error. Find out which dictionary will be created successfully and which one will give error and correct it :
dict1 = { (1, 2) : [1, 2], (3, 4) : [3, 4]} dict2 = { ([1], [2]) : [1,2], ([3], [4]) : [3, 4]}Why is following code not giving correct output even when 25 is a member of the dictionary?
dic1 = {'age': 25, 'name': 'xyz', 'salary': 23450.5} val = dic1['age'] if val in dic1: print("This is member of the dictionary") else : print("This is not a member of the dictionary")What is the output produced by the following code :
d1 = {5 : [6, 7, 8], "a" : (1, 2, 3)} print(d1.keys()) print(d1.values())