December 2018
Beginner to intermediate
796 pages
19h 54m
English
The defaultdict data type is one of my favorites. It allows you to avoid checking if a key is in a dictionary by simply inserting it for you on your first access attempt, with a default value whose type you pass on creation. In some cases, this tool can be very handy and shorten your code a little. Let's see a quick example. Say we are updating the value of age, by adding one year. If age is not there, we assume it was 0 and we update it to 1:
>>> d = {}>>> d['age'] = d.get('age', 0) + 1 # age not there, we get 0 + 1>>> d{'age': 1}>>> d = {'age': 39}>>> d['age'] = d.get('age', 0) + 1 # age is there, we get 40>>> d{'age': 40}
Now let's see how it would work with a defaultdict data type. The second line is actually the short version ...
Read now
Unlock full access