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 «