• Python Snacks
  • Posts
  • Using the `get` method to fetch values from a Python dictionary

Using the `get` method to fetch values from a Python dictionary

Here's a quick tutorial as to why you should use this versus a try and except block.

When I first started Python programming and I always used to write my value-fetching-in-a-dictionary code like this:

my_dict = {
    'one' : 1,
    'two' : 2,
    'three' : 3
}

# Method 1: Using `try` and `except`
def get_key(key) -> str:
    try:
        return my_dict[key]
    except:
        return 'Key not defined.'

While this is a completely valid way of fetching values in the given dictionary, there’s a few issues with this:

  1. The try and except block, while more explicit with what you want, makes the code less-readable.

  2. Usage of a try/except block could potentially mask errors. While the example doesn’t reflect a scenario, it could make debugging more difficult.

  3. While it’s small, there’s performance issues with this. The try/except block does require more overhead because it has to catch and raise an exception.

I was told to use the .get() method instead. If we were to keep the same logic from above but change the function:

my_dict = {
    'one' : 1,
    'two' : 2,
    'three' : 3
}

# Method 2: Using `.get()`
def get_key(key) -> str:
    return my_dict.get(key, 'Key not defined.')

Not only does implementing the method eliminate the points I listed above, but it also adds the following value:

  1. You’ll have more control over the default value; in this case, Key not defined is the default value if the key does not exist.

  2. The code becomes even more explicit as to what you want, whereas the try/except block could imply that you’re catching a special edge case.

For more information about the .get() method, see W3 School's article.

📧 Join the Python Snacks Newsletter! 🐍

Want even more Python-related content that’s useful? Here’s 3 reasons why you should subscribe the Python Snacks newsletter:

  1. Get Ahead in Python with bite-sized Python tips and tricks delivered straight to your inbox, like the one above.

  2. Exclusive Subscriber Perks: Receive a curated selection of up to 6 high-impact Python resources, tips, and exclusive insights with each email.

  3. Get Smarter with Python in under 5 minutes. Your next Python breakthrough could just an email away.

You can unsubscribe at any time.

Interested in starting a newsletter or a blog?

Do you have a wealth of knowledge and insights to share with the world? Starting your own newsletter or blog is an excellent way to establish yourself as an authority in your field, connect with a like-minded community, and open up new opportunities.

If TikTok, Twitter, Facebook, or other social media platforms were to get banned, you’d lose all your followers. This is why you should start a newsletter: you own your audience.

This article may contain affiliate links. Affiliate links come at no cost to you and support the costs of this blog. Should you purchase a product/service from an affiliate link, it will come at no additional cost to you.

Reply

or to participate.