Python Basics

Check if a python dictionary contains a key

Dictionary are the one of the very powerful data listing option available in python. Unlike list and tuple, dictionary hold data in key and value pair. So in some cases the developer may want to find out if a certain key is present.

Lets see how to check if a python dictionary contains a key?

Example

registration_numbers={

“rahul”:”kk98ki11″,

“ajay”:”kk98ki12″,

“vijay”:”kk98ki13″,

“neha”:”kk98ki14″,

“simran”:”kk98ki15″

}

# The above is an example of dictionary variable. It holds name and respective registration numbers.

# Lets check if neha and her registration number exist in the dictionary or not?

#solution 1

if neha in registration_numbers:

print(“neha and her registration number exists”)

#solution 2

if registration_numbers.has_key(“neha”):

print(“neha and her registration number exists”)

#Solution 2

if “neha” in registration_numbers.keys():

print(“neha and her registration number exists”)

I have discussed about three different solutions to find out if the key “neha” is present in the dictionary registration_numbers.