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
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
item in stockisTruewhenitemis one of the keys ofstock.- Only inside the
ifis it safe to readstock[item], since the key is known to exist. inlooks at keys only, so40 in stockisFalseeven though 40 is one of the values; usestock.values()to search the values.- Checking a key with
inis very fast, even for a dictionary with millions of keys.
Other ways to write it
Using get()
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
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.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises