tip: dictionary get() works like getattr

You can’t use getattr() to look stuff up in a dictionary.
But the ‘default’ feature of getattr() is so useful.
What’s the dict way to do the same thing?

This is one of those posts that I’m writing because I keep having to look it up.
So if I write it, I’ll remember it. Hopefully.

getattr

I’ve been using the ‘default’ parameter to getattr for some time, and it’s super handy.
This is handy in lots of places, and avoids having to wrap things in try/except blocks.

A simple example:

Can be replaced with:

dictionary get()

But getattr doesn’t work as I’d expect for dictionaries.
It does something, just not what I would expect.
Mostly, it DOESN’T look up items.

Use get() instead.
Replace:

With:

If you like this…

Get notified of new posts, delivered to your inbox. No spam. Not very frequent.

Comments

  1. Ross Reedstrom says

    One step further – if you need a non-None default, and want to actually store it:
    foo = aDict.setdefault(‘FOO’,’bar’)

    I have used it build lists in dictionaries:
    aDict.setdefault(‘foo’,[]).append(‘bar’)

  2. Raf says

    The default replacement value for get() is None. Hence, your example above could be shortened to:
    foo = aDictionary.get(‘FOO’)

    • says

      Raf, thanks for pointing that out.

      Perhaps None is bad for the example.
      When I am using this, I’m usually using a non-Null default value, such as an empty list, or empty string, etc.

Leave a Reply