How To Check if a Given Key Already Exists in a Dictionary

Two different ways to check

Jonathan Hsu
Oct 25 · 2 min read
Photo by Pisit Heng on Unsplash

A dictionary is a mutable — it has an unordered set of keys and values. Knowing how to check if a key exists is critical, both prior to assigning values, to avoid overwriting existing data, and when accessing values, to ensure the key exists.

Use the in keyword or the .get() method to inspect a dictionary for a given key.


The “in” Keyword

person = {
"first_name": "Sarah",
"last_name": "Kerrigan",
"nickname": "Queen of Blades"
}
print("nickname" in person.keys()) # True
print("age" in person.keys()) # False

Notice that the .keys() method is used to return the keys from our dictionary as a list of strings. We can speed this technique up because in may also be used directly with dictionaries. When querying a dictionary, the keys, and not the values, are searched.

person = {
"first_name": "Sarah",
"last_name": "Kerrigan",
"nickname": "Queen of Blades"
}
print("nickname" in person) # True
print("age" in person) # False

The .get() Method

person = {
"first_name": "Sarah",
"last_name": "Kerrigan",
"nickname": "Queen of Blades"
}
print(person['age'])"""
Traceback (most recent call last):
File "medium.py", line 7, in <module>
print(person['age'])
KeyError: 'age'
"""

To avoid this scenario, you could use the above method to check for a key first. However, this can become very repetitive.

person = {
"first_name": "Sarah",
"last_name": "Kerrigan",
"nickname": "Queen of Blades"
}
if "age" in person:
print(person['age'])
if "first_name" and "last_name" in person:
print(first_name + " " + last_name)

Alternatively, use .get() which will not cause an exception if the key does not exist. The method requires a single string (the key that will be retrieved) and accepts an optional second argument, which will be used as the default value when the key is not found. When a default value is not specified, None will be returned by .get() when the key is not found.

person = {
"first_name": "Sarah",
"last_name": "Kerrigan",
"nickname": "Queen of Blades"
}
middle_name = person.get("middle_name","") # empty string
print(person.get("age")) # None

Better Programming

Advice for programmers.

Jonathan Hsu

Written by

I’m a black belt problem-solver (literally). I enjoy the taking on new challenges, building skills, and sharing what I’ve learned. 🥋

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade