Python Dictionary:Typeerror: Unhashable Type: 'List'

How to overcome TypeError: unhashable type: 'list'

As indicated by the other answers, the error is to due to k = list[0:j], where your key is converted to a list. One thing you could try is reworking your code to take advantage of the split function:

# Using with ensures that the file is properly closed when you're done
with open('filename.txt', 'rb') as f:
d = {}
# Here we use readlines() to split the file into a list where each element is a line
for line in f.readlines():
# Now we split the file on `x`, since the part before the x will be
# the key and the part after the value
line = line.split('x')
# Take the line parts and strip out the spaces, assigning them to the variables
# Once you get a bit more comfortable, this works as well:
# key, value = [x.strip() for x in line]
key = line[0].strip()
value = line[1].strip()
# Now we check if the dictionary contains the key; if so, append the new value,
# and if not, make a new list that contains the current value
# (For future reference, this is a great place for a defaultdict :)
if key in d:
d[key].append(value)
else:
d[key] = [value]

print d
# {'AAA': ['111', '112'], 'AAC': ['123'], 'AAB': ['111']}

Note that if you are using Python 3.x, you'll have to make a minor adjustment to get it work properly. If you open the file with rb, you'll need to use line = line.split(b'x') (which makes sure you are splitting the byte with the proper type of string). You can also open the file using with open('filename.txt', 'rU') as f: (or even with open('filename.txt', 'r') as f:) and it should work fine.

typeerror: unhashable type: 'list' ,How to count occurrence of elements in python list and save it in dictionary?

You're getting that error because you're using x (which is defined in the caller's scope as an empty list) as the key. A list can't be used as a dictionary key because lists are mutable and keys must be immutable. That aside, though, you don't want a list to be the key (and certainly not x which is just an empty list), but rather the specific item that you counted, which would be i.

An easier solution is to use the Counter class:

>>> from collections import Counter
>>> Counter(l)
Counter({1: 3, 3: 2, 5: 2, 2: 1})

Python, TypeError: unhashable type: 'list'

The problem is that you can't use a list as the key in a dict, since dict keys need to be immutable. Use a tuple instead.

This is a list:

[x, y]

This is a tuple:

(x, y)

Note that in most cases, the ( and ) are optional, since , is what actually defines a tuple (as long as it's not surrounded by [] or {}, or used as a function argument).

You might find the section on tuples in the Python tutorial useful:

Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

And in the section on dictionaries:

Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().


In case you're wondering what the error message means, it's complaining because there's no built-in hash function for lists (by design), and dictionaries are implemented as hash tables.

unhashable type: 'list' in making a dictionary

You are using your variable grid as it was a list, but it is a list of lists. You should iterate twice (you are only iterating one - over the lists)

The following code should work:

from random import randint
d={}
grid = [[randint(1, 5)for j in range(5)] for i in range(5)]

print(grid)

for array in grid: # iterate over every list inside the list of lists
for element in array: # iterate over every element inside a list
if element in d: # check if element is a key in d
d[element]=d[element]+1
else:
d[element]=1

EDIT: By sugestion of scott-hunter, I include the code with defaultdicts:

In defaultdicts, you initially state the default value of a key

from random import randint
from collections import defaultdict

d = defaultdict(lambda: 0)
grid = [[randint(1, 5)for j in range(5)] for i in range(5)]

print(grid)

for array in grid:
for element in array:
d[element]=d[element]+1

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

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)

Getting TypeError: unhashable type: 'list' in python dict

The problem is in this line

newk = [k[k.find('-',5)+1:]] 

newk is a list, not a string. Remove square brackets and your code should work.

There is a good explanation why lists can't be used as dictionary keys - https://wiki.python.org/moin/DictionaryKeys

Also I would recommend you to use dictionary comprehensions to create a new dictionary and bind aDict name to it.

aDict = {
'form-1-device': ['2'],
'form-0-test_group': ['1'],
'form-1-test_scenario': ['3'],
}

aDict = {k[k.find('-',5)+1:]:v for k, v in aDict.iteritems()}


Related Topics



Leave a reply



Submit