The Python dictionary get() method returns the value associated with a specific key. get() accepts two arguments: the key for which you want to search and a default value that is returned if the key is not found.
Retrieving a value for a specified key in a dictionary is a common operation when you’re working with dictionaries. For instance, you may be a tea shop owner and want to retrieve how many orders you had for white tea.
That’s where the Python dictionary get—dict.get()—method comes in: it returns the value for a specified key in a dictionary.
This method will only return a value if the specified key is present in the dictionary, otherwise it will return None.
In this tutorial, we will explore Python’s built-in dict.get() method and how you can use it to retrieve specific values from Python dictionaries. In addition, we’ll walk through examples of the dict.get() method in real programs to explain how it works in more depth.
Python Dictionary Refresher
Python dictionaries map keys to values and create key-value pairs that can be used to store data. Dictionaries are often used to hold related data. For instance, a dictionary could act as the record of a student at a school or information about a book in a library. I want to give the writers direct feedback so that they can improve instead of just fixing errors.
Here’s an example of a dictionary in Python that holds information about a specific tea sold in a tea shop:
black_tea = { 'supplier': 'Twinings', 'name': 'English Breakfast' 'boxes_in_stock': 12, 'loose_leaf': True }
The words to the left of the colons are dictionary keys, which in the above example are: supplier, name, boxes_in_stock, and loose_leaf.
Python Dictionary get() Method
The Python dictionary get() method retrieves a value mapped to a particular key. get() will return None if the key is not found, or a default value if one is specified.
The syntax for the dict.get() method in Python is as follows:
dictionary_name.get(name, value)
The dict.get() method accepts two parameters:
- name is the name of the key whose value you want to return. This parameter is required.
- value is the value to return if the specified key does not exist. This defaults to None. This parameter is optional.
You can retrieve items from a dictionary using indexing syntax. As we’ll discuss later in this guide, this can sometimes be counterintuitive.
Most beginners learn indexing first. But, once you know how to use get() you’ll probably find yourself using it more often than dictionary indexing to retrieve a value.
Get Values from Dictionary in Python: Example
Let’s walk through an example to demonstrate the dict.get() method in action. Say that we are operating a tea house, and we want to see how many people ordered matcha_green_tea last month.
This data is part of a dictionary that stores the names of teas as keys. The number of people who ordered specific teas are stored as values.
We could use the following code to retrieve how many people ordered matcha_green_tea:
teas = { 'english_breakfast': 104, 'matcha_green_tea': 26, 'green_tea': 29, 'decaf_english_breakfast': 51, 'assam': 48 } matcha = teas.get('matcha_green_tea') print(matcha)
Our code returns: 26.
At the start of our code, we define a Python variable called teas. This dictionary stores information about tea orders in our tea house.
Then, we use the dict.get() method on our teas dictionary to retrieve the value associated with the matcha_green_tea key. Finally, we print out the value to the console using a Python print() statement.
Let’s consider another example. Let’s say that we have a dictionary for each tea that we sell. These dictionaries contain information about their respective teas, including:
- Who the supplier is.
- What we name the tea.
- How many boxes we have in stock.
- Whether it is loose-leaf.
The following is our dictionary for the black tea we sell:
black_tea = { 'supplier': 'Twinings', 'name': 'English Breakfast' 'boxes_in_stock': 12, 'loose_leaf': True }
Suppose we want to find out whether our black tea is stored as a loose-leaf tea. We could do so using this code:
get_loose_leaf = black_tea.get('loose_leaf') print(get_loose_leaf)
Our code returns a Python boolean value: True.
We use the dict.get() method to retrieve the value of loose_leaf in the black_tea dictionary. The fact that our code returns True tells us that our black tea is stored as a loose-leaf tea. We would receive a None value if our tea did not exist in the dictionary.
Python Dictionary get(): Default Value
The dict.get() method accepts an optional second parameter. This parameter specifies the value that should be returned if a key cannot be found within a dictionary. This lets you change the default response of None if a value is not found.
So, let’s say that we want to retrieve taste_notes from a dictionary that stores information about the black tea our tea house stocks. We only just hired our tea taster tasked with writing those descriptions, so they don’t exist for all teas yet. Tasting notes do not exist for our black tea.
To avoid our program returning None, we want our code to return a notification message. This message should inform us that the taste notes are not available for that tea yet.
"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"
Venus, Software Engineer at Rockbot
The below program retrieves taste_notes from a dictionary containing information about our black tea. Our program returns a message if the taste notes are not available:
black_tea = { 'supplier': 'Twinings', 'name': 'English Breakfast' 'boxes_in_stock': 12, 'loose_leaf': True } get_loose_leaf = black_tea.get('taste_notes', 'Taste notes are not available for this tea yet.') print(get_loose_leaf)
Our black_tea dictionary does not contain a value for the key taste_notes, so our program returns the following message:
Taste notes are not available for this tea yet.
Python Dictionary get() vs. dict[key]
One common method used to access a value in a dictionary is to reference its value using the dict[key] syntax.
The difference between the dict[key] syntax and dict.get() is that if a key is not found using the dict[key] syntax, a KeyError is raised. If you use dict.get() and a key is not found, the code will return None (or a custom value, if you specify one).
Here’s what happens if we try to use the dict[key] syntax to retrieve taste_notes from a dictionary that lacks that key:
black_tea = { 'supplier': 'Twinings', 'name': 'English Breakfast' 'boxes_in_stock': 12, 'loose_leaf': True } print(black_tea['taste_notes'])
Because taste_notes is not present in our black_tea dictionary, our code returns the following error:
KeyError: 'taste_notes'
Conclusion
The dict.get() method is used in Python to retrieve a value from a dictionary. dict.get() returns None by default if the key you specify cannot be found. With this method, you can specify a second parameter that will return a custom default value if a key is not found.
You can also use the dict[key] syntax to retrieve a value from a dictionary. If you use the dict[key] syntax and the program cannot find the key you specify, the code will return a KeyError. Because this syntax returns an error, using the dict.get() method is often more appropriate.
Now you’re ready to start retrieving values from a Python dictionary using dict.get() like a pro! For guidance on Python courses and learning resources, check out our How to Learn Python guide.
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.