-2

Easiest explained by example:

events = ['foo', 'bar', 'biz', 'foo', 'foo']
events_counter = {}
for event in events:
    if event not in events_counter: # {
        events_counter[event] = 1   # {
    else:                           # {
        events_counter[event] += 1  # {
print events_counter

# {'biz': 1, 'foo': 3, 'bar': 1}

Is there a way to implement the highlighted code in a more pythonic way? I feel like there should be a built-in function, i.e:

events_counter.count_up(event)

And yes, I do know I could just write my own procedure, thanks.

Raven
  • 648
  • 1
  • 7
  • 18

1 Answers1

7

Python has a built in Counter data structure for this:

from collections import Counter
events = ['foo', 'bar', 'biz', 'foo', 'foo']
cc = Counter(events)
print(cc)

Output:

Counter({'foo': 3, 'bar': 1, 'biz': 1})
GWW
  • 43,129
  • 11
  • 115
  • 108