Home > Back-end >  How do you create a function that takes an argument and returns a dictionary of character counts in
How do you create a function that takes an argument and returns a dictionary of character counts in

Time:01-31

I would like to create a function that takes an argument and creates a dictionary where:

I) the keys are the individual characters of the argument, and

ii) the values represent the number of occurrences of that particular character in the argument.

I have been shown the example below, which although works - lines 4 and 5 don't seem instinctual to me.

Perhaps it's because I'm new to coding. Why should the code need to check an empty dictionary? Is there a more intuitive way?

def count_letters(text):
  result = {}
  for letter in text:
    if letter not in result:
      result[letter] = 0
    result[letter]  = 1
  return result

print(count_letters("Python"))

CodePudding user response:

If you don't check if letter is in result first, then

result[letter]  = 1

will raise a KeyError, because there's no value to increment yet.


This is a common pattern (add a key if it doesn't exist yet, then do something with its value) captured by the defaultdict type.

from collections import defaultdict

def count_letters(text):
    result = defaultdict(int)
    for letter in text:
        # If letter isn't in result yet, implicitly execute
        # result[letter] = int() first.
        # int() returns 0.
        result[letter]  = 1
    return result

Counting items in an iterable value is also a common pattern, so it might not be surprising that there's a type for that as well.

from collections import Counter

def count_letters(text):
    # Counter is a subclass of dict,
    # so you can do with it anything you
    # would do with the dict.
    return Counter(text)
  •  Tags:  
  • Related