Computer Science
The following code is giving some error. Find out the error and correct it.
d1 = {"a" : 1, 1 : "a", [1, "a"] : "two"}
Answer
This type of error occurs when a mutable type is used as a key in dictionary. In d1, [1, "a"] is used as a key which is a mutable type of list. It will generate the below error:
TypeError: unhashable type: 'list'
This error can be fixed by using a tuple as a key instead of list as shown below:
d1 = {"a" : 1, 1 : "a", (1, "a") : "two"}
Related Questions
Discuss the working of copy( ) if
(i) the values are of immutable types,
(ii) the values are of mutable types.
Which of the following will result in an error for a given valid dictionary D?
- D + 3
- D * 3
- D + {3 : "3"}
- D.update( {3 : "3"})
- D.update { {"3" : 3}}
- D.update("3" : 3)
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]}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"}