Python: Using a dictionary to count the items in a list [duplicate]

0 votes
asked Aug 16, 2010 by sophie

This question already has an answer here:

8 Answers

0 votes
answered Jan 16, 2010 by nick-t
L = ['apple','red','apple','red','red','pear']
d = {}
[d.__setitem__(item,1+d.get(item,0)) for item in L]
print d 

Gives {'pear': 1, 'apple': 2, 'red': 3}

0 votes
answered Aug 16, 2010 by bernie
>>> L = ['apple','red','apple','red','red','pear']
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for i in L:
...   d[i] += 1
>>> d
defaultdict(<type 'int'>, {'pear': 1, 'apple': 2, 'red': 3})
0 votes
answered Aug 16, 2010 by odomontois

in 2.7 and 3.1 there is special Counter dict for this purpose.

>>> from collections import Counter
>>> Counter(['apple','red','apple','red','red','pear'])
Counter({'red': 3, 'apple': 2, 'pear': 1})
0 votes
answered Aug 17, 2010 by stefano-palazzo

I always thought that for a task that trivial, I wouldn't want to import anything. But i may be wrong, depending on collections.Counter being faster or not.

items = "Whats the simpliest way to add the list items to a dictionary "

stats = {}
for i in items:
    if i in stats:
        stats[i] += 1
    else:
        stats[i] = 1

# bonus
for i in sorted(stats, key=stats.get):
    print("%d×'%s'" % (stats[i], i))

I think this may be preferable to using count(), because it will only go over the iterable once, whereas count may search the entire thing on every iteration. I used this method to parse many megabytes of statistical data and it always was reasonably fast.

0 votes
answered Aug 5, 2011 by mmmdreg

I like:

counts = dict()
for i in items:
  counts[i] = counts.get(i, 0) + 1

.get allows you to specify a default value if the key does not exist.

0 votes
answered Aug 7, 2012 by riviera

How about this:

src = [ 'one', 'two', 'three', 'two', 'three', 'three' ]
result_dict = dict( [ (i, src.count(i)) for i in set(src) ] )

This results in

{'one': 1, 'three': 3, 'two': 2}

0 votes
answered Aug 6, 2015 by pradyot

Consider collections.Counter (available from python 2.7 onwards). https://docs.python.org/2/library/collections.html#collections.Counter

0 votes
answered Aug 29, 2016 by ashish-k

Simply use list property count\

i = ['apple','red','apple','red','red','pear']
d = {x:i.count(x) for x in i}
print d

output : {'pear': 1, 'apple': 2, 'red': 3}

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...