
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Check whether given key already exists in a dictionary in Python
The dictionary containers in pipeline old both key and values as pairs. Sometimes we may need to find if a given key is already present in the dictionary. In this article we will see the various ways to check for the presence of a key in a dictionary.
With in
This is a very straightforward way in which we just check for the presence of the key in the dictionary using in operator. If the the keys part of dictionary we print the result as present else absent.
Example
Adict = {'Mon':3,'Tue':5,'Wed':6,'Thu':9} print("The given dictionary : ",Adict) check_key = "Fri" if check_key in Adict: print(check_key,"is Present.") else: print(check_key, " is not Present.")
Output
Running the above code gives us the following result −
The given dictionary : {'Thu': 9, 'Wed': 6, 'Mon': 3, 'Tue': 5} Fri is not Present.
With dict.keys
The dict.keys() method gives us all the keys that are present in a given dictionary. We can use the in operator how to find out if the given key belongs to the given dictionary.
Example
Adict = {'Mon':3,'Tue':5,'Wed':6,'Thu':9} print("The given dictionary : ",Adict) check_key = "Wed" if check_key in Adict.keys(): print(check_key,"is Present.") else: print(check_key, " is not Present.")
Output
Running the above code gives us the following result −
The given dictionary : {'Thu': 9, 'Wed': 6, 'Mon': 3, 'Tue': 5} Wed is Present.
- Related Articles
- How to check if a given key already exists in a Python dictionary?
- How to check if a key exists in a Python dictionary?
- Check if a given key exists in Java HashMap
- Check whether the Dictionary has the specified key or not in C#
- How to check if a user email already exists in Laravel?
- Check whether a value exists in JSON object?
- Check if a particular key exists in Java LinkedHashMap
- How do I check whether a file exists using Python?
- C++ Program to Check Whether a Hamiltonian Cycle or Path Exists in a Given Graph
- Check if a list exists in given list of lists in Python
- Check if a triplet with given sum exists in BST in Python
- Check if given multiple keys exist in a dictionary in Python
- Accessing Key-value in a Python Dictionary
- How to check if a key exists in a map in Golang?
- Java Program to check if a particular key exists in TreeMap

Advertisements