Shreya Rajpal
Shreya Rajpal

Reputation: 3

Python Dictionaries : Using Tuple as a key, getting error 'unhashale type : list'

So I'm using a dictionary where the key is a set of two integers, and the value of each key is one integer, defined below:

for line in f:
    l = line.split(':')
    m = float(l[0])
    c = float(l[1])
    lines[m] = [c]
    lineIndices[(m,c)] = i
    i += 1

So, m and c are make the key tuple, and i is the value for a tuple.

When I try retrieving the value of 'i' by using m & c, I get an error.

def getIndex(m):
    c = lines[m]
    i = lineIndices.get((m,c))

Error:

TypeError: unhashable type: 'list'

I can't figure out why this is happening, as I am using a tuple, not a list. Also, the error only occurs while trying to get the value by key, not while defining the value. Any ideas?

Upvotes: 0

Views: 177

Answers (1)

khelwood
khelwood

Reputation: 59093

Here are some lines from the code you quoted:

lines[m] = [c]

This assigns a list containing just your float c to lines[m]

c = lines[m]

This assigns that list to c. Those two steps are like

c = [ c ]

Now, in

i = lineIndices.get((m,c))

Part of the key is now a single-element list. But lists are unhashable, hence the error.

Presumably the first assignment should be

lines[m] = c

Upvotes: 4

Related Questions