Using "get()" to Return a Default Value from a Python Dict
Skills:
Python for Data90%
Key Takeaways
This video demonstrates how to use the get() method in Python dictionaries to return a default value when a key is not found, providing a clean and efficient solution for handling missing keys.
Full Transcript
hey there is Daniel with another quick Python tip so many of you are probably familiar with pythons dictionaries and I want to show you a quick tip today where we talk about the get method that's available on any Python dictionary and its default argument because in a lot of situations especially if you're dealing with text processing can be really helpful so I tried coming up with a simple example to show how how you can use the get method and I came up with this example where we have a dictionary that's called name for user ID where it basically maps from a integer user ID to the user's name right and you can imagine this comes from a database or whatever like it's it's it could be a real data structure that you have somewhere in your script or your Python application and so now what we want to do is we want to write a function that we're gonna call greeting that just takes a user ID and what we want that function to do is to return a greeting for that user and probably the simplest way we could think of implementing that which is be you know some kind of format string where we say hi and then substitute the user's name and we just go name for user ID and look up the name based on the user ID right so if we do this and let's just actually define that and then play with it for a bit and we pass in a valid user ID to work fine however if we're passing in an invalid ID this is going to blow up so now it would be really interesting or really good for us for that function to actually return something useful if the user ID is not available and so you might think you know the first thing we could do here is pull we're just going to check if the user ID is actually in the dictionary so it should say okay if user ID in name for user ID then we're going to return we have and if not we're just going to return kind of sensible default right okay so now we still get the same behavior if I put in a valid user ID I get my high Ellis I put in an invalid user ID I get my hi there which it's kind of what I want okay so so this would work so now the challenge with this implementation that we have is that it could be a little bit more pretty so the first thing is that it's it's kind of not good style to do a membership chick here so a little bit more pythonic option would be to actually just try and grab the the name for the user ID and if it fails we would erase an exception or kind of catch it would race and exception itself we would catch the exception and it just returned to default so a better implementation could look like this where we would have this triblock and we just say okay just try to do this and if we get a key error we'll just return hi there and now this works the way we expect it to work but this could still be a little bit shorter okay so there's actually a better way we can do this because most of this is actually built into Python because it's such a common thing so I hinted at this in the beginning every dictionary in Python has a get method on it and you can see the the doc string forget here and the way it works is that you can pass a key to it you know it's it's so instead of doing instead of doing this where the key would be the key would be the user ID we can use the get method and pass the same key and we get the same result okay so that seems pretty useless right like why not use the shorthand square bracket syntax for that so now the cool thing is that you can pass a default that will get returned if if the key could not be found right so what we can do now is we can specify a default let's say there and then if the idea is found we get the value for that key but if we pass in an invalid ID or you know when I would trigger a key error we get the default so with that get method it becomes a lot easier to define our greeting greeting method we could just say okay return hi and then we do the string substitution whoops we'll do the string substitution and then we're just going to say name for user ID get passing the ID and we're going to make the default there right now when we run greeting we pass a valid ID it works as expected when we pass an invalid ID we get our expected result and so now this is really short makes it uses just a standard Python feature we don't have to deal with either doing a membership check or actually writing out that exception block so it's really nice and clean everyone's gonna understand it because it's a standard Python standard library feature and for that reason I think this is probably the best implementation for this little example cool I hope you enjoyed that and if you want more and then feel free to subscribe or check out my blog
Original Description
Here's a common situation working with dictionaries in Python: You want to look up the value of a key and if the key doesn't exist then you want to fall back to a default value.
There's many different ways to deal with that and some are considered anti-patterns. One of the best solutions is to use the "get()" method and its ability to pass on a default value. This video explains how to get better at working with dicts by learning how to use "get()" more effectively :) Also check out my tutorial here which contains some more background info on the topic: https://dbader.org/blog/python-dict-get-default-value
► Weekly Tips for Python Developers: https://dbader.org/newsletter
Playlist
Uploads from Real Python · Real Python · 16 of 60
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
▶
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
A better Python REPL – bpython vs python interpreter
Real Python
Introducing large-type.com – A Utility Website
Real Python
Reading Hacker News Without Wasting Tons of Time
Real Python
Forward References and Python 3 Type Hints
Real Python
Using Sublime Text as your Git Editor
Real Python
Python Code Linting and Auto-Complete for Sublime Text
Real Python
Make your Python Code More Readable with Custom Exceptions
Real Python
Write Better Tests with Sublime Text's Split Layout Feature
Real Python
How to Use Sublime Text from the Command Line
Real Python
Rename Variables with Multiple Selection in Sublime Text
Real Python
Sublime Text Settings for Writing PEP 8 Python
Real Python
Write Cleaner Python with Sublime Text's Indent Guides
Real Python
Sublime Text Whitespace Settings for Python Development
Real Python
Function Argument Unpacking in Python
Real Python
Python Code Review: Debugging and Refactoring "Conway's Game of Life" + Automated Tests
Real Python
Using "get()" to Return a Default Value from a Python Dict
Real Python
A Python Shorthand for Swapping Two Variables
Real Python
Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Real Python
Click & Jump to Test Failures from the Command Line (iTerm2)
Real Python
Setting up Sublime Text for Python Developers
Real Python
Sublime Text + Python Guide Overview
Real Python
Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Real Python
Type-Checking Python Programs With Type Hints and mypy
Real Python
A Shorthand for Merging Dictionaries in Python 3.5+
Real Python
Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Real Python
My Python Code Looks Ugly and Confusing – Help!
Real Python
Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Real Python
Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Real Python
Programmer Portfolio – Example and Walkthrough
Real Python
How to Get Your 1st Speaking Gig at a Tech Conference
Real Python
How to Build Your Public Speaking Skills as a Developer
Real Python
The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
Real Python
Setting up Sublime Text for Python Developers – Lesson #1
Real Python
Cool New Features in Python 3.6
Real Python
"is" vs "==" in Python – What's the Difference? (And When to Use Each)
Real Python
Emulating switch/case Statements in Python with Dictionaries
Real Python
Python Function Argument Unpacking Tutorial (* and ** Operators)
Real Python
What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
Real Python
A Crazy Python Dictionary Expression ?!
Real Python
String Conversion in Python: When to Use __repr__ vs __str__
Real Python
Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Real Python
Optional Arguments in Python With *args and **kwargs
Real Python
Python Context Managers and the "with" Statement (__enter__ & __exit__)
Real Python
Installing Python Packages with pip and virtualenv / venv
Real Python
"For Each" Loops in Python with enumerate() and range()
Real Python
Python Code Review: LibreOffice Automation and the Python Standard Library
Real Python
Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Real Python
Python Tutorial: List Comprehensions Step-By-Step
Real Python
Leveraging Python's Implicit "return None" Statements
Real Python
What's the meaning of underscores (_ & __) in Python variable names?
Real Python
Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Real Python
Writing automated tests for Python command-line apps and scripts
Real Python
How to find great Python packages on PyPI, the Python Package Repository
Real Python
Immutable vs Mutable Objects in Python
Real Python
PyPI vs Warehouse, the Next-Generation Python Package Repository
Real Python
pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
Real Python
My Experience at PyCon 2017 in Portland
Real Python
Pylint Tutorial – How to Write Clean Python
Real Python
"Reverse a List in Python" Tutorial: Three Methods & How-to Demos
Real Python
Python Refactoring: "while True" Infinite Loops & The "input" Function
Real Python
More on: Python for Data
View skill →Related Reads
📰
📰
📰
📰
Meshy AI 3D Generator Review 2026: 185 MB Per House, $193 to Ship It
Medium · AI
5 Claude Tricks That Feel Almost Like Cheating
Medium · Data Science
[Video] I Tested Grok 4.7 With One Simple Job: Turn My vi Task Files Into a Bash Agenda
Dev.to AI
oh-my-agent 15: HyperFrames replaces Remotion, Serena guard ships
Dev.to AI
🎓
Tutor Explanation
DeepCamp AI