Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to hash a tuple of lists in Python

I originally had a list of lists and I wanted to create a dictionary with keys as these lists of lists but I know lists cannot be hashed. So I tried converting the outer list into a tuple and then hashing it, but compiler still says TypeError: unhashable type: 'list'. So I was wondering if there is any way I could create y using x where x is as follows?:

x = ([0, 0], [1, 1], [2, 0], [3, 1])
y = {}
y[x] = 1
print('y: ', y)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can make the inner lists into tuples, which will make the whole key immutable:

x=[[0, 0], [1, 1], [2, 0], [3, 1]]
key = tuple(tuple(l) for l in x)

y={}
y[key]=1

print('y: ',y)
# y:  {((0, 0), (1, 1), (2, 0), (3, 1)): 1}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading