Home > Software engineering >  How to hash a tuple of lists in Python
How to hash a tuple of lists in Python

Time:03-20

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)

CodePudding user response:

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}
  • Related