+2 votes
in Programming Languages by (51.1k points)
I am creating a dictionary and want list as key of my dictionary. For example:

aa[[45,2003]] =123, aa[[50,2013]] =143, etc.

But the above code gives error: "TypeError: unhashable type: 'list'". How can I use list as key of the dictionary?

1 Answer

0 votes
by (157k points)

From the error, you can understand that list is not allowed. Instead you can use tuple and reference the items in the tuple using index. Check the following example:

>>> aa={}
>>> aa[(45,2003)]=123
>>> aa[(50,2013)]=143
>>> for k,v in aa.items():
...     print(k[0],v)
(50, 143)
(45, 123)

Hope it helps.