Python3: TypeError: unhashable type: 'list' when using Counter

TJ1 picture TJ1 · Mar 22, 2014 · Viewed 13.4k times · Source

I am using Python 3 and I have this code:

from collections import Counter
c = Counter([r[1] for r in results.items()])

But when I run it I get this error:

Traceback (most recent call last):
  File "<pyshell#100>", line 1, in <module>
    c = Counter([r[1] for r in results.items()])
  File "C:\Python33\lib\collections\__init__.py", line 467, in __init__
    self.update(iterable, **kwds)
  File "C:\Python33\lib\collections\__init__.py", line 547, in update
    _count_elements(self, iterable)
TypeError: unhashable type: 'list'

Why am I getting this error? The code was originally written for Python 2, but I am using it in Python 3. Is there anything that changed between Python 2 and 3?

Answer

warvariuc picture warvariuc · Mar 22, 2014

The docs say:

A Counter is a dict subclass for counting hashable objects.

In your case it looks like results is a dict containing list objects, which are not hashable.

If you are sure that this code worked in Python 2, print results to see its content.

Python 3.3.2+ (default, Oct  9 2013, 14:50:09) 
>>> from collections import Counter
>>> results = {1: [1], 2: [1, 2]}
>>> Counter([r[1] for r in results.items()])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/vic/projects/venv/trains/lib/python3.3/collections/__init__.py", line 467, in __init__
    self.update(iterable, **kwds)
  File "/home/vic/projects/venv/trains/lib/python3.3/collections/__init__.py", line 547, in update
    _count_elements(self, iterable)
TypeError: unhashable type: 'list'

By the way, you can simplify your construction:

Counter(results.values())