0

I have a list with 0, 1 and 2, I want to create a dict with the count of each. This is my code,

count_map = {}
for i in my_list:
  if i in count_map:
     count_map[i] += 1
  else:
     count_map[i] = 1

My question is how can I write this code more pythonically.

Cœur
  • 34,719
  • 24
  • 185
  • 251
Melissa Stewart
  • 3,063
  • 10
  • 40
  • 84

3 Answers3

6

You can use collections.Counter to do that for you:

from collections import Counter
count_map = Counter(my_list)

You can type cast it to dictionary by using dict(Counter(my_list))

Mohd
  • 5,370
  • 7
  • 18
  • 29
2

I would increment value in your dictionary this way in one line:

count_map = {}
for i in my_list:
  count_map[i] = count_map.get(i,0) + 1
OLIVER.KOO
  • 5,276
  • 2
  • 26
  • 53
1

Using a dict cmprh :

l=[1,1,1,2,1,2,5,4,2,5,1,4,5,2]
{i:l.count(i) for i in set(l)}

Output :

{1: 5, 2: 4, 4: 2, 5: 3}
khelili miliana
  • 3,537
  • 1
  • 14
  • 25