1

I often find my self using a dict to count the occurences of something, and I wonder if there is a way of doing this more smooth without using exceptions.

count_dict = {} 
for file in files:
    ############
    #parse file#
    ############
    for line in lines:
        tokens = line.split()
        if "something" in tokens:
            try:
                count_dict[tokens[0]] += 1
            except KeyError:
                count_dict[tokens[0]] = 1
jensjorda
  • 183
  • 2
  • 3
  • 10

1 Answers1

5

Python has a class specifically for this: collections.Counter.

count_dict = Counter(str.split())
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895