1
from numpy.random import randint

orig_list = randint(0, 99, 1000)
dictionary = {}

for item in orig_list:
    if not item in dictionary:
        dictionary[item] = 0
    dictionary[item] += 1

I know I can loop through the list and do dictionary[item] += 1, but is there no faster way?

MasonMac
  • 137
  • 1
  • 8
  • 2
    That sounds like an ideal use for `collections.Counter`. – jasonharper May 26 '20 at 23:03
  • 1
    You want [`collections.Counter`](https://docs.python.org/2/library/collections.html#collections.Counter), which is a specialized dict for counting things. Also, the construct you want for creating it without a for-loop is a ***dict comprehension*** (or ***Counter comprehension***, in this case). – smci May 26 '20 at 23:05

0 Answers0