Python Training by 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.

» Subscribe to the dbader.org YouTube Channel for more Python tutorials.

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]
    else:
        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):
    try:
        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 «

<strong><em>Improve Your Python</em></strong> with a fresh 🐍 <strong>Python Trick</strong> 💌 every couple of days

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:
  • Comprehending Python’s Comprehensions – One of my favorite features in Python are list comprehensions. They can seem a bit arcane at first but when you break them down they are actually a very simple construct.
  • 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.
  • Python’s Functions Are First-Class – Python’s functions are first-class objects. You can assign them to variables, store them in data structures, pass them as arguments to other functions, and even return them as values from other functions.
  • Python Decorators: A Step-By-Step Introduction – Understanding decorators is a milestone for any serious Python programmer. Here’s your step-by-step guide to how decorators can help you become a more efficient and productive Python developer.
  • Dictionaries, Maps, and Hash Tables in Python – Need a dictionary, map, or hash table to implement an algorithm in your Python program? Read on to see how the Python standard library can help you.

📦🐍 Which frameworks and libraries are the most important to know to be considered an effective Python dev? Here’s how you go from “writing scripts” to “building applications” with Python, master the tools of the trade for Dependency Management, and become an expert at picking quality Python libraries: » Click here to learn more

Latest Articles:
Unique Mousepads for Pythonistas

Unique Mousepads for Pythonistas
Rest Your Hand Comfortably & Write Beautiful Python
» Browse Python Mousepads at Nerdlettering.com

← Browse All Articles