Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Solution: count characters with default dict

  • collections
  • defaultdict
from collections import defaultdict

text = """
This is a very long text.
OK, maybe it is not that long after all.
"""

# print(text)
count = defaultdict(int)

for char in text:
    if char == '\n':
        continue
    count[char] += 1

for key in sorted( count.keys() ):
    print("'{}' {}".format(key, count[key]))
  • The previous solution can be slightly improved by using defaultdict from the collections module.
  • count = defaultdict(int) creates an empty dictionary that has the special feature that if you try to use a key that does not exists, it pretends that it exists and that it has a value 0.
  • This allows us to remove the condition checking if the character was already seen and just increment the counter. The first time we encounter a charcter the dictionary will pretend that it was already there with value 0 so everying will work out nicely.