-6

I need to find all unique values in python list, and if there was a duplicate write how many of them, example:

['apple','cherry','coffee','apple','coffee','coffee']

and the output should be:

apple 2
cherry 1
coffee 3
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
user3057314
  • 65
  • 1
  • 7
  • 5
    Dup: [How can I count the occurrences of a list item in Python?](http://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item-in-python) – Ashwini Chaudhary Jan 02 '14 at 11:18

2 Answers2

2
>>> from collections import Counter
>>> Counter(['apple','cherry','coffee','apple','coffee','coffee'])
Counter({'coffee': 3, 'apple': 2, 'cherry': 1})
>>> for k,v in _.items():
...   print k,v
... 
cherry 1
coffee 3
apple 2
wim
  • 338,267
  • 99
  • 616
  • 750
1

Looks like a homework... Here's a straight forward approach:

lst = ['apple','cherry','coffee','apple','coffee','coffee']

res = {}
for obj in lst:
    if obj not in res:
        res[obj] = 0
    res[obj] += 1

print res
freakish
  • 54,167
  • 9
  • 132
  • 169