Python: Check if Key Exists in Dictionary

python_tutorials

Introduction

Dictionary (also known as ‘map’, ‘hash’ or ‘associative array’) is a built-in Python container that stores elements as a key-value pair.

Just like other containers have numeric indexing, here we use keys as indexes. Keys can be numeric or string values. However, no mutable sequence or object can be used as a key, like a list.

In this article, we’ll take a look at how to check if a key exists in a dictionary in Python.

In the examples, we’ll be using this fruits_dict dictionary:

fruits_dict = dict(apple= 1, mango= 3, banana= 4)
{'apple': 1, 'banana': 4, 'mango': 3}

Check if Key Exists using in Operator

The simplest way to check if a key exists in a dictionary is to use the in operator. It’s a special operator used to evaluate the membership of a value.

Here it will either evaluate to

 

 

To finish reading, please visit source site