Check keys in Python dictionary

Dictionaries Python are structures that store sets of key/value pairs. When we operate with them it will be highly recommended to check keys in the dictionary Python to avoid execution errors.

The first thing will be to define a dictionary. In this case we start from the following dictionary:

colors = {'red':'red','blue':'blue','green':'green'}

In this dictionary Python the keys will be the names of the colors in Spanish, while the values ​​will be the names of the colors in English.

If we execute the following statement:

print colors['red']

There will be no problem, since the color exists, and the statement will return the value in English.

However, if we execute the following statement:

print colors['yellow']

Our program will have an error while running. And, of course, we don’t want these things to happen. That is why before manipulating a dictionary key in Python, either to access its value or to delete it we must verify that the key exists.

To check keys in dictionary Python we are going to rely on the in operator using the following structure:

if  in 
      

Thus, if we want to check if the ‘yellow’ key exists we must encode the following:

if 'yellow' in colors:
    print colors['yellow']
else:
    print 'There is no translation for the color yellow'

We see that we only access the content of the key if it exists.

This is why it is highly recommended to check keys in the dictionary Python using the in operator.