1

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
  • 37,241
  • 25
  • 195
  • 267
Melissa Stewart
  • 3,483
  • 11
  • 49
  • 88

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,523
  • 7
  • 19
  • 30
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,654
  • 3
  • 30
  • 62
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,730
  • 2
  • 15
  • 28