I'd like to count the frequency of items in a list by calling a collections.Counter. The trick is that my list itself contains lists:
Given:
[[1,"a"], [2,"b"], [3,"c"], [1,"a"], [1,"a"]
Produce:
{
([1,"a"], 3),
([2,"b"], 1),
([3,"c"], 1)
}
When I instantiate Counter using my list, I get TypeError: unhashable type: 'list'.
Can Counter do what I want? Is there some other (reasonably efficient) method for doing this?
Counter
returns a hash table. For this to work the keys (what is getting counted) have to be hashable. Unfortunately lists are not hashable, which is why you are seeing your error.
One work-around would be to cast each internal list to a tuple
.
from collections import Counter
x = [[1,"a"], [2,"b"], [3,"c"], [1,"a"], [1,"a"]]
Counter(tuple(item) for item in x)
# returns:
Counter({(1, 'a'): 3, (2, 'b'): 1, (3, 'c'): 1})
Typically only immutable types are hashable. You can convert your list to tuples using map.
from collections import Counter
x = [[1,"a"], [2,"b"], [3,"c"], [1,"a"], [1,"a"]
print(Counter(map(tuple, x)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With