Using "get()" to Return a Default Value from a Python Dict

Real Python · Beginner ·🛠️ AI Tools & Apps ·10y ago

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
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Real Python · Real Python · 16 of 60

1 A better Python REPL – bpython vs python interpreter
A better Python REPL – bpython vs python interpreter
Real Python
2 Introducing large-type.com – A Utility Website
Introducing large-type.com – A Utility Website
Real Python
3 Reading Hacker News Without Wasting Tons of Time
Reading Hacker News Without Wasting Tons of Time
Real Python
4 Forward References and Python 3 Type Hints
Forward References and Python 3 Type Hints
Real Python
5 Using Sublime Text as your Git Editor
Using Sublime Text as your Git Editor
Real Python
6 Python Code Linting and Auto-Complete for Sublime Text
Python Code Linting and Auto-Complete for Sublime Text
Real Python
7 Make your Python Code More Readable with Custom Exceptions
Make your Python Code More Readable with Custom Exceptions
Real Python
8 Write Better Tests with Sublime Text's Split Layout Feature
Write Better Tests with Sublime Text's Split Layout Feature
Real Python
9 How to Use Sublime Text from the Command Line
How to Use Sublime Text from the Command Line
Real Python
10 Rename Variables with Multiple Selection in Sublime Text
Rename Variables with Multiple Selection in Sublime Text
Real Python
11 Sublime Text Settings for Writing PEP 8 Python
Sublime Text Settings for Writing PEP 8 Python
Real Python
12 Write Cleaner Python with Sublime Text's Indent Guides
Write Cleaner Python with Sublime Text's Indent Guides
Real Python
13 Sublime Text Whitespace Settings for Python Development
Sublime Text Whitespace Settings for Python Development
Real Python
14 Function Argument Unpacking in Python
Function Argument Unpacking in Python
Real Python
15 Python Code Review: Debugging and Refactoring "Conway's Game of Life" +  Automated Tests
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
Using "get()" to Return a Default Value from a Python Dict
Real Python
17 A Python Shorthand for Swapping Two Variables
A Python Shorthand for Swapping Two Variables
Real Python
18 Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Real Python
19 Click & Jump to Test Failures from the Command Line (iTerm2)
Click & Jump to Test Failures from the Command Line (iTerm2)
Real Python
20 Setting up Sublime Text for Python Developers
Setting up Sublime Text for Python Developers
Real Python
21 Sublime Text + Python Guide Overview
Sublime Text + Python Guide Overview
Real Python
22 Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Real Python
23 Type-Checking Python Programs With Type Hints and mypy
Type-Checking Python Programs With Type Hints and mypy
Real Python
24 A Shorthand for Merging Dictionaries in Python 3.5+
A Shorthand for Merging Dictionaries in Python 3.5+
Real Python
25 Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Real Python
26 My Python Code Looks Ugly and Confusing – Help!
My Python Code Looks Ugly and Confusing – Help!
Real Python
27 Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Real Python
28 Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Real Python
29 Programmer Portfolio – Example and Walkthrough
Programmer Portfolio – Example and Walkthrough
Real Python
30 How to Get Your 1st Speaking Gig at a Tech Conference
How to Get Your 1st Speaking Gig at a Tech Conference
Real Python
31 How to Build Your Public Speaking Skills as a Developer
How to Build Your Public Speaking Skills as a Developer
Real Python
32 The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
Real Python
33 Setting up Sublime Text for Python Developers – Lesson #1
Setting up Sublime Text for Python Developers – Lesson #1
Real Python
34 Cool New Features in Python 3.6
Cool New Features in Python 3.6
Real Python
35 "is" vs "==" in Python – What's the Difference? (And When to Use Each)
"is" vs "==" in Python – What's the Difference? (And When to Use Each)
Real Python
36 Emulating switch/case Statements in Python with Dictionaries
Emulating switch/case Statements in Python with Dictionaries
Real Python
37 Python Function Argument Unpacking Tutorial (* and ** Operators)
Python Function Argument Unpacking Tutorial (* and ** Operators)
Real Python
38 What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
Real Python
39 A Crazy Python Dictionary Expression ?!
A Crazy Python Dictionary Expression ?!
Real Python
40 String Conversion in Python: When to Use __repr__ vs __str__
String Conversion in Python: When to Use __repr__ vs __str__
Real Python
41 Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Real Python
42 Optional Arguments in Python With *args and **kwargs
Optional Arguments in Python With *args and **kwargs
Real Python
43 Python Context Managers and the "with" Statement (__enter__ & __exit__)
Python Context Managers and the "with" Statement (__enter__ & __exit__)
Real Python
44 Installing Python Packages with pip and virtualenv / venv
Installing Python Packages with pip and virtualenv / venv
Real Python
45 "For Each" Loops in Python with enumerate() and range()
"For Each" Loops in Python with enumerate() and range()
Real Python
46 Python Code Review: LibreOffice Automation and the Python Standard Library
Python Code Review: LibreOffice Automation and the Python Standard Library
Real Python
47 Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Real Python
48 Python Tutorial: List Comprehensions Step-By-Step
Python Tutorial: List Comprehensions Step-By-Step
Real Python
49 Leveraging Python's Implicit "return None" Statements
Leveraging Python's Implicit "return None" Statements
Real Python
50 What's the meaning of underscores (_ & __) in Python variable names?
What's the meaning of underscores (_ & __) in Python variable names?
Real Python
51 Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Real Python
52 Writing automated tests for Python command-line apps and scripts
Writing automated tests for Python command-line apps and scripts
Real Python
53 How to find great Python packages on PyPI, the Python Package Repository
How to find great Python packages on PyPI, the Python Package Repository
Real Python
54 Immutable vs Mutable Objects in Python
Immutable vs Mutable Objects in Python
Real Python
55 PyPI vs Warehouse, the Next-Generation Python Package Repository
PyPI vs Warehouse, the Next-Generation Python Package Repository
Real Python
56 pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
Real Python
57 My Experience at PyCon 2017 in Portland
My Experience at PyCon 2017 in Portland
Real Python
58 Pylint Tutorial – How to Write Clean Python
Pylint Tutorial – How to Write Clean Python
Real Python
59 "Reverse a List in Python" Tutorial: Three Methods & How-to Demos
"Reverse a List in Python" Tutorial: Three Methods & How-to Demos
Real Python
60 Python Refactoring: "while True" Infinite Loops & The "input" Function
Python Refactoring: "while True" Infinite Loops & The "input" Function
Real Python

Learn how to use the get() method in Python dictionaries to return a default value when a key is not found, making your code more efficient and robust.

Key Takeaways
  1. Define a dictionary with key-value pairs
  2. Use the get() method to retrieve a value from the dictionary
  3. Specify a default value to return if the key is not found
  4. Handle missing keys using the get() method
💡 The get() method provides a clean and efficient way to handle missing keys in a dictionary, eliminating the need for explicit exception handling or membership checks.

Related Reads

📰
Meshy AI 3D Generator Review 2026: 185 MB Per House, $193 to Ship It
Learn how Meshy AI 3D Generator works and its implications on data storage and shipping costs
Medium · AI
📰
5 Claude Tricks That Feel Almost Like Cheating
Boost productivity with Claude by using 5 tricks that simplify workflows and enhance efficiency
Medium · Data Science
📰
[Video] I Tested Grok 4.7 With One Simple Job: Turn My vi Task Files Into a Bash Agenda
Learn how to use Grok 4.7 to automate task management by converting vi task files into a Bash agenda
Dev.to AI
📰
oh-my-agent 15: HyperFrames replaces Remotion, Serena guard ships
Learn about the latest updates in oh-my-agent CLI 15.0.0, including the replacement of Remotion with HyperFrames and new features for code intelligence and Serena daemons
Dev.to AI
Up next
How to Get Your Brand Cited by ChatGPT, Claude and Gemini
Arvow
Watch →