How to Check if a Given Key Exists in a Dictionary in Python


In this example, we will learn the methods to check whether a given key exists in the dictionary.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

dict1 = {'a': 11, 'b': 22, 'c': 33, 'd': 44}
key = input("Please input the key to be checked: ")
if key in dict1.keys():
    print("The key exists and its value is: ", dict1[key])
else:
    print("The key does not exist.")

Output:

Case 1:
Please input the key to be checked: c
The key exists and its value is: 33

Case 2:
Please input the key to be checked: g
The key does not exist.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments