When you first start learning Python, chances are you write dictionary access as such:

dictionary['key']

This is a valid way to retrieve the associated value in the dictionary, but it does come with a major drawback: what happens if the key doesn’t exist?

Take the following dictionary, for example:

cloud_information = {
    "name" : "cumulonimbus",
    "height" : "1000m",
    "is_raining" : False 
}

Let’s say that I were to access the dictionary to get the name of the cloud:

dictionary["Height"]

This will throw an error, as Height does not exist (but height does). The capitalization does matter and I’ll explain why below if you’d like a deeper dive into this topic.

Using the .get() method will help avoid this error and give us something to fall back on in case the key doesn’t exist in our dictionary. Generally, this is the preferred way of going about accessing dictionaries:

# Argument 1: the key value you're wanting to retrieve from the dictionary
# Argument 2: a "fallback" value if the key doesn't exist
cloud_information.get("Height", "Field does not exist")

I personally never use dictionary access without .get() for this exact reason, even if it’s a key I’d expect to be in the dictionary; things happen and I’d want my logging to pick up on it.

Alternatively, you could wrap this statement in a try/except statement, but this does provide more code overhead and a presents a pattern I try to avoid unless it’s necessary:

try:
    return dictionary['height']
except KeyError as e:
    return "Field does not exist"

How dictionaries work under the hood (and why they’re so quick!)

It might make sense to us humans that we want height regardless of capitalization, but computers don’t understand human text - it understands numbers.

Taking a peek under the hood, each key in our dictionary is stored in a “bucket”, which contains the key’s hash, a pointer to the key object, and a pointer to the value object:

Example bucket

When you index the dictionary (i.e. cloud_information[‘height’]), the requested key, height, hash is computed.

It uses this hash to jump directly to the bucket there the key should live, checks that the key matches, and then returns the value.

And if you’re someone who likes talking time complexity, this is why all dictionary lookups are constant time (O(1)) 😃

📧 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

Avatar

or to participate

Keep Reading