Python Check if Key Exists in Dictionary

Minh Vu

By Minh Vu

Updated Oct 25, 2023

Figure: Python Check if Key Exists in Dictionary

Disclaimer: All content on this website is derived directly from my own expertise and experiences. No AI-generated text or automated content creation tools are used.

It's Minh Vu again here. This time, I will show you how to check if a key exists in a Python dictionary.

In short, there are 3 ways to check if a key exists in a Python dictionary: using the in keyword, the get() method, and the try-except block.

Let's get started!

Contents

What is a Python dictionary?

A Python dictionary is a collection of key-value pairs. Each key-value pair is separated by a colon :.

For example:

info = { "name": "Minh Vu", "age": 21, "country": "Vietnam" }

The info is a dictionary that contains my information, including my name, age, and country.

But sometimes, the dictionary doesn't contain all those information, for example:

info = { "name": "Minh Vu", "age": 21 }

The "country" key is missing here. So you will get the KeyError exception if you try to access it:

print(info["country"]) # KeyError: 'country'

That's why we need to check if a key exists in a Python dictionary before accessing it.

How to Fix the KeyError Exception

To avoid the KeyError exception, you can check if a key exists in a Python dictionary using 3 ways:

  • Use the in keyword (simplest way)
  • Use the get() method
  • Use the try-except block

Using the in Keyword

The in keyword is used to check if an element is in a list.

So, first we need to get the list of keys in the dictionary. Fortunately, this can be done easily in Python:

info = { "name": "Minh Vu", "age": 21, "country": "Vietnam" } keys = info.keys() print(keys) # dict_keys(['name', 'age', 'country'])

Then we can use the in keyword to check if a key exists in the dictionary:

info = { "name": "Minh Vu", "age": 21, "country": "Vietnam" } key1 = "country" key2 = "city" keys = info.keys() if key1 in keys: print(f"info['{key1}'] = {info[key1]}") else: print(f"info['{key1}'] doesn't exist") # info['country'] = Vietnam if key2 in keys: print(f"info['{key2}'] = {info[key2]}") else: print(f"info['{key2}'] doesn't exist") # info['city'] doesn't exist

As you can see, the key1 variable, which is the "country" key, exists in the dictionary, so we can access it without getting the KeyError exception.

On the other hand, the key2 variable, which is the "city" key, doesn't exist in the dictionary, so we get the info['city'] doesn't exist message.

Using the get() Method

The get() method is used to get the value of a key in a dictionary and return None if the key doesn't exist.

info = { "name": "Minh Vu", "age": 21, "country": "Vietnam" } key1 = "country" key2 = "city" print(f"info['{key1}'] = {info.get(key1)}") print(f"info['{key2}'] = {info.get(key2)}") # info['country'] = Vietnam # info['city'] = None

You can also change what the get() method returns if the key doesn't exist by passing a default value to it:

info = { "name": "Minh Vu", "age": 21, "country": "Vietnam" } key = "city" print(f"info['{key}'] = {info.get(key, 'Not Exists')}") # ^ # default value # info['city'] = Not Exists

This method can be useful when you want to return a default value if the key doesn't exist. For example:

counter = {} counter['a'] = counter.get('a', 0) + 1

The counter dictionary is used to count the occurences of 0 and 1. And it's better than this code:

counter = {} if 'a' in counter: counter['a'] += 1 else: counter['a'] = 1

Using the try-except Block

The try-except block is used to catch the exception and handle it.

info = { "name": "Minh Vu", "age": 21, "country": "Vietnam" } key = "city" try: print(f"info['{key}'] = {info[key]}") except KeyError: print(f"info['{key}'] doesn't exist") # info['city'] doesn't exist

I highly recommend you to use the try-except everytime, not only for checking if a key exists in a Python dictionary, but also for other cases.

Conclusion

To recap, there are 3 ways to check if a key exists in a Python dictionary:

  • Use the in keyword
  • Use the get() method
  • Use the try-except block

Thanks for reading!

Minh Vu

Minh Vu

Software Engineer

Hi guys 👋, I'm a developer specializing in Elastic Stack and Next.js. My blog shares practical tutorials and insights based on 3+ years of hands-on experience. Open to freelance opportunities — let's get in touch!

Comments

Be the first to comment!

Leave a Comment

Receive Latest Updates 📬

Get every new post, special offers, and more via email. No fee required.