Dan Bader

Using get() to return a default value from a Python dict

Python’s dictionaries have a “get” method to look up a key while providing a fallback value. This short screencast tutorial gives you a real-world example where this might come in handy.

Imagine we have the following data structure mapping user IDs to user names:

name_for_userid = {
    382: "Alice",
    950: "Bob",
    590: "Dilbert",

Now we’d like to write a function greeting() which returns a greeting for a user given their user ID. Our first implementation might look something like this:

def greeting(userid):
    return "Hi %s!" % name_for_userid[userid]

This implementation works if the user ID is a valid key in name_for_userid, but it throws an exception if we pass in an invalid user ID:

>>> greeting(382)
"Hi Alice!"

>>> greeting(33333333)
KeyError: 33333333

Let’s modify our greeting function to return a default greeting if the user ID cannot be found. Our first idea might be to simply do a “key in dict” membership check:

def greeting(userid):
    if userid in name_for_userid:
        return "Hi %s!" % name_for_userid[userid]
        return "Hi there!"

>>> greeting(382)
"Hi Alice!"

>>> greeting(33333333)
"Hi there!"

While this implementation gives us the expected result, it isn’t great:

  • it’s inefficient because it queries the dictionary twice
  • it’s verbose as part of the greeting string are repeated, for example
  • it’s not pythonic – the official Python documentation recommends an “easier to ask for forgiveness than permission” (EAFP) coding style:

“This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false.” (Python glossary: “EAFP”)

Therefore a better implementation that follows EAFP could use a try…except block to catch the KeyError instead of doing a membership test:

def greeting(userid):
        return "Hi %s!" % name_for_userid[userid]
    except KeyError:
        return "Hi there"

Again, this implementation would be correct – but we can come up with a cleaner solution still! Python’s dictionaries have a get() method on them which supports a default argument that can be used as a fallback value:

def greeting(userid):
    return "Hi %s!" % name_for_userid.get(userid, "there")

When get() is called it checks if the given key exists in the dict. If it does, the value for that key is returned. If it does not exist then the value of the default argument is returned instead.

As you can see, this implementation of greeting works as intended:

>>> greeting(950)
"Hi Bob!"

>>> greeting(333333)
"Hi there!"

Our final implementation of greeting() is concise, clean, and only uses features from the Python standard library. Therefore I believe it is the best solution for this particular situation.

P.S. If you enjoyed this screencast and you’d like to see more just like it then subscribe to my » YouTube channel with free screencasts and video tutorials for Python developers «

📘 Python Tricks: The Book — A Buffet of Awesome Python Features: My new book that teaches you the coolest aspects of Python with short and easy to digest examples. » Click here to get a free sample chapter

Improve Your Python with a fresh 🐍 Python Trick 💌 every couple of days

🔒 No spam ever. Unsubscribe any time.

This article was filed under: programming, python, and video.

Related Articles:
Latest Articles:
  • Context Managers and the “with” Statement in Python – The “with” statement in Python is regarded as an obscure feature by some. But when you peek behind the scenes of the underlying Context Manager protocol you’ll see there’s little “magic” involved.
  • Installing Python and Pip on Windows – In this tutorial you’ll learn how to set up Python and the Pip package manager on Windows 10, completely from scratch.
  • Sublime Text Settings for Writing Clean Python – How to write beautiful and clean Python by tweaking your Sublime Text settings so that they make it easier to adhere to the PEP 8 style guide recommendations.
  • How Sublime Text’s Preferences Work – Sublime Text uses a powerful text-based settings system that can be a little intimidating when you encounter it for the first time. This article gives an overview of the system and points out some common mistakes to avoid.
  • Writing Clean Python With Namedtuples – Python comes with a specialized “namedtuple” container type that doesn’t seem to get the attention it deserves. It’s one of these amazing features in Python that’s hidden in plain sight.
  • Lambda Functions in Python: What Are They Good For? – An introduction to “lambda” expressions in Python: What they’re good for, when you should use them, and when it’s best to avoid them.
← Browse All Articles