Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filling a dictionary of counts from an iterable

What is the most pythonic way to fill a dictionary of counts from an iterable?

I know that there is collections.Counter, with which I can do

counter = Counter(iterable)

and then use counter just like a dictionary having as keys the distinct items of iterable and as values their counts.

But there must be a pythonic way of doing the same thing with a regular dict, something more compact than

count = {}
for item in iterable:
    if item not in count:
        count[item] = 1
    else:
        count[item] += 1

What is it?

like image 763
Walter Tross Avatar asked Nov 17 '25 04:11

Walter Tross


1 Answers

One simple way:

count = {}
for item in iterable:
    count[item] = count.get(item, 0) + 1

But generally, you should just use a collections.Counter. You don't use a Counter "just like" a dict, it is a dict.

like image 82
juanpa.arrivillaga Avatar answered Nov 19 '25 21:11

juanpa.arrivillaga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!