AI Features

Using defaultdict

Understand how to use the defaultdict with the help of multiple examples.

We’ve seen how to use the setdefault method to set a default value if a key doesn’t exist, but this can get a bit monotonous if we need to set a default value every time we look up a value. Let’s have a look at an example to better understand this concept.

Example: Count letters

For example, if we’re writing code that counts the number of times a letter occurs in a given sentence, we could do the following:

from __future__ import annotations
def letter_frequency(sentence: str) -> dict[str, int]:
frequencies: dict[str, int] = {}
for letter in sentence:
frequency = frequencies.setdefault(letter, 0)
frequencies[letter] = frequency + 1
return frequencies

Every time we access the dictionary, we need to check that it already has a value; if not, set it to ...

Ask