Computer Science

The following code is giving some error. Find out the error and correct it.
d1 = {"a" : 1, 1 : "a", [1, "a"] : "two"}

Python Dictionaries

20 Likes

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

Answered By

14 Likes


Related Questions