Table of Contents
Motivation
When learning a specific language it is essential that you also learn the built-in functionality which gives you leverage.
In Python there are often so called pythonic ways to solve problems like lambdas, filter function or enumerate.
Tools that save you time when addressing real world problems.
Use case
Sometimes you want to do some basic tasks like e.g. counting the frequency of words in a sentence.
A dictionary can be a good fit for a data structure:
my_string = "the quick brown fox jumps over the lazy dog."
words = my_string.split()
count = dict()
for word in words:
if word in count:
count[word] += 1
else:
count[word] = 1
When a word is already a key in the dictionary you can increment the value with += shorthand.
If the word isn’t in the dict you need to initially insert it and assign the value 1
defaultdict
With the defaultdict you can save the conditional logic.
from collections import defaultdict
my_string = "the quick brown fox jumps over the lazy dog."
words = my_string.split()
count = defaultdict(int)
for word in words:
count[word] += 1
You need to initialize the defaultdict with the datatype you want as value.
Further Reading
https://docs.python.org/3/library/collections.html#collections.defaultdict