A woman looking for a key in a messy place

Code Snippets: Python – The Magic Of The get() Method And Default Argument Unveiled

In this article, we will discover how to use Python get() method and how to give a default value, if the key is not present in the dictionary.

Why is this relevant?

Imagine you are a consultant working on some kind of back-end solution for a supermarket. a situation in which you want to create a switch logic, so you would like to improve something that looks like this:

if product_id == 1598:
    product_des = 'whole wheat pasta'
elif product_id == 4865:
    product_des = 'eggs pasta - tagliatelle'
elif product_id == 9853:
    product_des = 'macaroni and cheese'
else:
    product_des = 'unknown product'

A more Pythonic approach

You should know that there is another way to create a switch statement by taking advantage of dictionaries and the get() method. Let’s first have a look at what a dictionary is, and why they are so widely used in Python.

What is a Dictionary?

In Python, a dictionary is an unordered collection of items. They are stored as key-value pairs, which means that we can search for a certain element’s value by knowing the key of that element. Dictionaries have the property to be mutable, meaning that we can always alter them by adding, removing or altering elements inside them.

How does the get() work?

The get() method is a powerful function that allows retrieving the value of a given key in a dictionary. If the key exists in the dictionary, the method returns the actual value of the given key, otherwise, we can set up a default value, when the key is not found.

Let’s rework the example

Let’s now apply the method I just explained to the given example. This is the reworked code:

# The get() method on dicts
# and its "default" argument

description_for_productid = {
    1598: 'whole wheat pasta',
    4865: 'eggs pasta - tagliatelle',
    9853: 'macaroni and cheese',
}
def get_product_descprition(productid):
    return f"Product description for product {productid}: {description_for_productid.get(productid, 'unknown product')}"

>>> get_product_descprition(1598)
"Product description for product 1598: whoe wheat pasta"

>>> get_product_descprition(4865)
"Product description for product 4865: eggs pasta - tagliatelle"

>>> get_product_descprition(9999)
"Product description for product 9999: unknown product"

In the example, description_for_productid is our dictionary with product IDs as keys and their corresponding descriptions as values. The function get_product_description() takes a product ID as an argument, uses get() to retrieve the product description, and returns a string with the product ID and its description. If the product ID isn’t in our dictionary, it returns the string ‘unknown product’.

Benefits of the approach

By using the get() method, you reduce the need for multiple if-elif statements, making your code cleaner, more readable, and more efficient. Additionally, the method provides a safeguard against KeyError exceptions, improving your code’s robustness.

Further applications and use cases

Besides the product catalogue example shown here, you could use this method to manage user permissions in a web application, control the state in a game, or even parse complex JSON data from an API call.

Subscribe

Did you find value in this article? Don’t miss out on more insights like this. Sign up for my email newsletter and get the latest articles delivered right to your inbox!


Posted

in

by