shanky
shanky

Reputation: 801

Adding array to dictionary TypeError: unhashable type: 'list'

I am unable to add array [3,5] to dictionary linedict = {}. I have check with solution mentioned on Python: TypeError: unhashable type: 'list' but still error is coming (TypeError: unhashable type: 'list')

    links = [links[i:i+2] for i in range(0, len(links), 2)]

    for i in range(0, len(links), 1):
        print links[i]

        if links[i] not in linedict:#on this linme
          linedict[links[i]].append( prob) 

I want to create dictionary of [3,5] value 0.03.

Upvotes: 2

Views: 4920

Answers (2)

agrinh
agrinh

Reputation: 1905

Here's a simpler way using defaultdict from collections. I also did some few changes to your code that should make it clearer.

import collections

# use a default dict
linedict = collections.defaultdict(list)
# create your list of lists as before but convert them to tuples
links = [tuple(links[i:i+2]) for i in range(0, len(links), 2)]

# iterate over the lists directly
for link in links:
    print link
    linedict[link].append(prob)  # it's a default dict so you can append directly!

Upvotes: 2

Mark Ransom
Mark Ransom

Reputation: 308216

You're already printing links[i], so it should have come to your attention that each element of the links list is also a list.

A dictionary can't contain a list as a key, since dictionaries are based on a hash table and lists can't be hashed. Tuples can be hashed though, and they're very similar to lists, so you could try converting the list to a tuple.

Also you can't append to something that doesn't exist yet. The most straight-forward approach is to handle the two cases separately, assuming you want to capture every match and add it to a list. You could also use a defaultdict which would handle the first-time addition automatically, as suggested in the comments.

if tuple(links[i]) not in linedict:
    linedict[tuple(links[i])] = [prob]
else:
    linedict[tuple(links[i])].append(prob) 

Upvotes: 5

Related Questions