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