A dictionary is a valuable data structure in Python; it holds key-value pairs. During programming, there is often a need to extract the value of a given key from a dictionary; however, it is not always guaranteed that a specific key exists in the dictionary.
When you index a dictionary with a key that does not exist, it will throw an error.
Hence, it is a safe practice to check whether or not the key exists in the dictionary prior to extracting the value of that key. For that purpose, Python offers two built-in functions:
if
-in
statementhas_key()
if
-in
statementThis approach uses the if
-in
statement to check whether or not a given key exists in the dictionary.
The syntax below is used to look up a given key in the dictionary using an if
-in
statement:
The code snippet below illustrates the usage of the if
-in
statement to check for the existence of a key in a dictionary:
Fruits = {'a': "Apple", 'b':"Banana", 'c':"Carrot"}key_to_lookup = 'a'if key_to_lookup in Fruits:print "Key exists"else:print "Key does not exist"
has_key
methodThe has_key
method returns true if a given key is available in the dictionary; otherwise, it returns false.
See the syntax of the has_key
method below:
The code snippet below illustrates the usage of the has_key
method:
Fruits = {'a': "Apple", 'b':"Banana", 'c':"Carrot"}key_to_lookup = 'a'if Fruits.has_key(key_to_lookup):print "Key exists"else:print "Key does not exist"
Note: The method referred to in this answer, the Python
has_key
method, has deprecated and is not available in Python 3.
RELATED TAGS