-1

How do I count number of occurrences in a list and store the word and count value as a dict using python without using Counter function from collection library? E.g.: list = [a,a,a,b,b,c,c,c,c] result should be when I print dict a->3 b->2 c->4:

dict=[(word,list.count(word)) for word in list]

This doesn't seem to work.

ArifMustafa
  • 4,617
  • 5
  • 40
  • 48

1 Answers1

2

If you don't want to use Counter, then you can try dict comprehension combined with set() to avoid counting occurrences of the same word many times:

>>> lst = list("aaabbcccc")
>>> lst
['a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'c']
>>> {word: lst.count(word) for word in set(lst)}
{'a': 3, 'c': 4, 'b': 2}

Just keep in mind that while this method is pretty nice and clear, it's not the most efficient method and if your list is very large, you should use something faster.

pkacprzak
  • 5,537
  • 1
  • 17
  • 37