Using a dictionary to count the items in a list [duplicate]
Solution 1:
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})
Solution 2:
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.
Solution 3:
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}