Python: The Dictionary Playbook
I would still love to hear your feedback in the comments below. Enjoy!
I so often come across various kinds of boilerplate code regarding dictionaries in Python, that I decided to show some of it here and share the more concise way of performing the same operations. Presenting: The Dictionary Playbook.
1. The “Are You There?”
This one is pretty simple, but I’m amazed as to how it’s missed - finding out if a key exists in the dictionary.
The Lame Version
The Python Way
2. The “Yoda Test”
For those programmers who master the “Are You There” play, there’s usually another simple, yet annoying behavior. It doesn’t only apply to dicts, but it’s very common.
Do This You Must Not
English, Do You Speak It?
3. The “Get the Value Anyway”
This one is really popular. You have a dictionary and a key, and you want to modify the key’s value. For example, adding 1 to it (let’s say you’re counting something).
The Boilerplate
The Awesome Way
dct.get(key[, default])
returns dct[key]
if it exists, and default
if not.
The Even More Awesome
If you’re using Python 2.7 and you want to count up amounts of stuff, you can use Counter.
And here’s a more complete example:
4. The “Make It Happen”
Sometimes your dictionary contains mutable objects, and you want to initialize and modify them. Let’s say you’re sorting out some data into a dictionary where the values are lists (examples courtesy of this answer in Stack Overflow).
Spelling It Out
Getting Down with the Python
What setdefault(key, default)
does is returns dct[key]
if it exists, and if it doesn’t - sets it to default
and returns it. Compared to get
, it’s useful when the default
value is an object you can modify, so you don’t have to manually reinsert its modified version to the dictionary.
Rocking it Out
defaultdict
is pretty awesome. It’s pretty self-explanatory - it’s a dict
with default values. This means that every access to a key in dct
that doesn’t exist in the dictionary (that would usually raise a KeyError
) creates it with the default value. It’s as if every access to dct
is done with setdefault
.
One interesting use I’ve found for defaultdict
is when implementing sparse data structures. You set defaultdict
to the default value and use coordinates (or whatever is applicable) as the key. I’ve used this to represents multi-dimensional grids and it’s definitely easier than using intricately wrapped lists.
An even more interesting example of its use is the one-line tree definition.
Discuss this post at the comment section below.Follow me on Twitter and Facebook