Courtesy of Al Sweigart’s Invent With Python article from last year (via
Python Bytes #135), I just learned about a super nifty feature of Python’s
dictionaries: dict.setdefault
(built-in types docs) allows you to set the value of a key if it doesn’t
exist.
I do this all the time—in fact, I just pulled this out of the source for this very site:
for year in years:
try:
years_dict[year]
except KeyError:
years_dict[year] = 0
finally:
years_dict[year] += 1
But with dict.setdefault
magic, it’s so much neater:
for year in years:
years_dict.setdefault(year, 0)
years_dict[year] += 1
The second version is much clearer and more legible. Not only did the number of lines decrease from six to two, but the implementation itself makes it far more obvious what’s going on.
This is the kind of stuff I absolutely love about Python. And there’s so much of it that I’m still very much constantly learning. <3
Update:
Tyrel reminded me about collections.defaultdict
(collections docs), which is more performant.
It might be preferable if the dictionary can be defined as such:
from collections import defaultdict
years_dict = defaultdict(int)
for year in years:
years_dict[year] += 1
Thanks for reading! You can keep up with my writing via the feed or newsletter, or you can get in touch via email or Mastodon.