CBSE Class 11 Informatics Practices Question 50 of 66

Dictionary — Question 22

Back to all questions
22
Question

Question 12

The following code is giving some error. Find out the error and write the corrected code.

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"}