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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With