July 25, 2008

Python - Counting Items In A List

Counting items in a list...

Lets say you have a list like this:
foo = [1, 2, 1, 2, 1, 2, 1, 1]
... and you want to count the items in the list, ending up with a dictionary full of items (dict keys) and counts (dict values), like this:
{1: 5, 2: 3}
Here is an easy way to do it:
d = {}
for i in set(foo):
    d[i] = foo.count(i)
got anything more Pythonic?
Post a Comment