Vale
Vale

Reputation: 1033

How do I fix the error "unhashable type: 'list'" when trying to make a dictionary of lists?

I'm trying to make a dictionary of lists. The input I am using looks like this:

4
1: 25
2: 20 25 28
3: 27 32 37
4: 22

Where 4 is the amount of lines that will be outputted in that format. The first thing I did was remove the "#: " format and simply kept each line like so:

['25']
['20','25','28']
['27','32','37']
['22']

So finally the goal was to take those values and put them into a dictionary with their assigned value in the dictionary being the length of how many numbers they held.

So I wanted the dictionary to look like this:

['25'] : 1
['20','25','28'] : 3
['27','32','37'] : 3
['22'] : 1

However, when I tried to code the program, I got the error:

TypeError: unhashable type: 'list'

Here is my code:

def findPairs(people):
    pairs = {}
    for person in range(people):
        data = raw_input()

        #Remove the "#: " in each line and format numbers into ['1','2','3']
        data = (data[len(str(person))+2:]).split()
        options = len(data)

        pairs.update({data:options})

    print(pairs)
findPairs(input())

Does anyone know how I can fix this and create my dictionary?

Upvotes: 1

Views: 2533

Answers (2)

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52093

list is an unhashable type, you need to convert it into tuple before using it as a key in dictionary:

>>> lst = [['25'], ['20','25','28'], ['27','32','37'], ['22']]
>>> print dict((tuple(l), len(l)) for l in lst)
{('20', '25', '28'): 3, ('22',): 1, ('25',): 1, ('27', '32', '37'): 3}

Upvotes: 2

Eilit
Eilit

Reputation: 189

Lists are mutable, and as such - can not be hashed (what happens if the list is changed after being used as a key)?

Use tuples which are immutable instead:

d = dict()
lst = [1,2,3]
d[tuple(lst)] = "some value"
print d[tuple(lst)] # prints "some value"

Upvotes: 4

Related Questions