Abe
Abe

Reputation: 23918

python Counter for a list of lists?

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?

Upvotes: 6

Views: 6522

Answers (2)

GWW
GWW

Reputation: 44093

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)))

Upvotes: 4

James
James

Reputation: 36598

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})

Upvotes: 8

Related Questions