Editor

Python Program to Check if a Key Exists in a Dictionary

Beginner · Dictionaries

Before reading a value from a dictionary, it is often worth checking that its key is there, because asking for a missing key stops the program with a KeyError. This program checks keys with the in operator.

Program

check_key_in_dictionary.py
stock = {"apple": 40, "banana": 25, "mango": 0}
item = "banana" # or: item = input("Enter an item: ")
if item in stock:
print(item, "is in the dictionary, value:", stock[item])
else:
print(item, "is not in the dictionary")
# in checks the keys, not the values
print("Is grapes a key?", "grapes" in stock)
print("Is 40 a key?", 40 in stock)
print("Is 40 a value?", 40 in stock.values())
Output
banana is in the dictionary, value: 25
Is grapes a key? False
Is 40 a key? False
Is 40 a value? True

How it works

  1. item in stock is True when item is one of the keys of stock.
  2. Only inside the if is it safe to read stock[item], since the key is known to exist.
  3. in looks at keys only, so 40 in stock is False even though 40 is one of the values; use stock.values() to search the values.
  4. Checking a key with in is very fast, even for a dictionary with millions of keys.

Other ways to write it

Using get()

Using get()
stock = {"apple": 40, "banana": 25, "mango": 0}
print("apple:", stock.get("apple"))
print("grapes:", stock.get("grapes")) # None, and no error
print("grapes:", stock.get("grapes", 0)) # a default instead of None
# Careful: a value of 0 makes a key look missing in an if
if not stock.get("mango"):
print("get() makes mango look missing, but 'mango' in stock is", "mango" in stock)
Output
apple: 40
grapes: None
grapes: 0
get() makes mango look missing, but 'mango' in stock is True

get() returns None, or a default you choose, for a missing key instead of raising an error. Do not use if stock.get(key) to mean "the key exists", because a real value of 0 or "" fails that test.

Using try and except KeyError

Using try and except KeyError
stock = {"apple": 40, "banana": 25}
for item in ["apple", "kiwi"]:
try:
print(item, "->", stock[item])
except KeyError:
print(item, "-> not found")
Output
apple -> 40
kiwi -> not found

Reading the key directly and catching KeyError is a common Python style when the key is usually there.

Try it yourself

Change item to "Apple" with a capital A and explain why it is not found.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises