Check if a Given Key Already Exists in a Python Dictionary - GeeksforGeeks (2024)

Last Updated : 09 Aug, 2024

Summarize

Comments

Improve

Python dictionary can not contain duplicate keys so it is very crucial to check if a key is already present in the dictionary. If you accidentally assign a duplicate key value, the new value will overwrite the old one.

So in a given dictionary, our task is to check if the given key already exists in a dictionary or not. If present, print “present” and the value of the key. Otherwise, print “Not present”.

Example

Input : {'a': 100, 'b':200, 'c':300}, key = b
Output : Present, value = 200
Input : {'x': 25, 'y':18, 'z':45}, key = w
Output : Not present

How to Check If a Key Already Exists in a Dictionary

There can be different ways to check whether a given key Exists in a Dictionary, we have covered the following approaches:

  • Python Dictionary keys()
  • If and in
  • Python Dictionary has_key()
  • Python Dictionary get() Method
  • Python ‘KeyError’ Exception Handling
  • Python List count()

1. Check If the Key Exists Using keys() Method

keys() method returns a list of all the available keys in the dictionary. With the Inbuilt method keys(), use the if statement with the ‘in’ operator to check if the key is present in the dictionary or not.

Python
# Python3 Program to check whether a# given key already exists in a dictionary.def checkKey(dic, key): if key in dic.keys(): print("Present, ", end =" ") print("value =", dic[key]) else: print("Not present") # Driver Codedic = {'a': 100, 'b':200, 'c':300}key = 'b'checkKey(dic, key)key = 'w'checkKey(dic, key)

Output:

Present, value = 200
Not present

Time Complexity: O(n)
Auxiliary Space: O(1)

2. Check If the Key Exists Using if and in

This method uses the if statement to check whether the given key exists in the dictionary.

Python
def checkKey(dic, key): if key in dic: print("Present, ", end =" ") print("value =", dic[key]) else: print("Not present")# Driver Codedic = {'a': 100, 'b':200, 'c':300}key = 'b'checkKey(dic, key)key = 'w'checkKey(dic, key)

Output:

Present, value = 200
Not present

Time complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(n), to store the keys and values in the dictionary.

3. Check If theKey Exists Using has_key() Method

Using the has_key() method returns true if a given key is available in the dictionary, otherwise, it returns a false. With the Inbuilt method has_key(), use the if statement to check whether the key is present in the dictionary.

Note – has_keys() method has been removed from the Python3 version. Therefore, it can be used in Python2 only.

Python
def checkKey(dic, key): if dic.has_key(key): print("Present, value =", dic[key]) else: print("Not present")# Driver Functiondic = {'a': 100, 'b':200, 'c':300}key = 'b'checkKey(dic, key)key = 'w'checkKey(dic, key)

Output:

('Present, value =', 200)
Not present

4. Check If the Key Exists Using get() Method

The Inbuilt method get() returns a list of available keys in the dictionary. With keys(), use the if statement to check whether the key is present in the dictionary. If the key is present it will print “Present” otherwise it will print “Not Present”.

Python
dic = {'a': 100, 'b':200, 'c':300}# check if "b" is none or not.if dic.get('b') == None: print("Not Present")else: print("Present")

Output:

Present

5. Handling ‘KeyError’ Exception in Python

Use try and except to handle the KeyError exception to determine if a key is present in a diet. The KeyError exception is generated if the key you’re attempting to access is not in the dictionary.

Python
dictExample = {'Aman': 110, 'Rajesh': 440, 'Suraj': 990}# Example 1print("Example 1")try: dictExample["Kamal"] print('The key exists in the dictionary')except KeyError as error: print("The key doesn't exist in the dictionary")# Example 2print("Example 2")try: dictExample["Suraj"] print('The key exists in the dictionary')except KeyError as error: print("The given key doesn't exist in the dictionary")

Output:

Example 1
The key doesn't exist in the dictionary
Example 2
The key exists in the dictionary

6. Check If the Key Exists Using count() Method

count() method can be used to check if the key exists in the dictionary, if the count of the key is 1 then the key is present else, it is not.

Python
# Python3 Program to check whether a# given key already exists in a dictionary.# Driver Codedic = {'a': 100, 'b': 200, 'c': 300}key = 'b'x = list(dic.keys())res = "Not Present"if(x.count(key) == 1): res = "Present"print(res)

Output:

Present

In this article, we discussed about 6 methods that can be used to check if a given key exists in the dictionary. You can use any of the above methods to check if the key is present. Checking for keys is very important as a dictionary can not contain duplicate keys.

Similar Reads:

  • Python | Get key from value in Dictionary
  • Check if given multiple keys exist in a dictionary
  • Get dictionary keys as a list
  • Test if key exists in tuple keys dictionary

Check if a Given Key Already Exists in a Python Dictionary – FAQs

How to Check if a Key Already Exists in a Dictionary in Python?

To check if a key exists in a dictionary in Python, you can use several methods. The most common and straightforward methods are using the in keyword or the get method.

Using in:

my_dict = {'a': 1, 'b': 2, 'c': 3}
key_to_check = 'b'
if key_to_check in my_dict:
print(f"Key '{key_to_check}' exists.")
else:
print(f"Key '{key_to_check}' does not exist.")

Using get:

if my_dict.get(key_to_check) is not None:
print(f"Key '{key_to_check}' exists.")
else:
print(f"Key '{key_to_check}' does not exist.")

How Do You Check if a Dictionary Key is Empty in Python?

To check if a key in a dictionary exists and its value is empty (assuming empty means either None, an empty string, list, etc.), you can directly check the value after ensuring the key exists.

# Example dictionary
my_dict = {'a': '', 'b': [1, 2], 'c': None}

key_to_check = 'a'
if key_to_check in my_dict and not my_dict[key_to_check]:
print(f"Key '{key_to_check}' exists and is empty.")
else:
print(f"Key '{key_to_check}' is not empty or does not exist.")

How Do You Check if a Value Exists in a List in Python?

To check for the existence of a value in a list in Python, use the in keyword, which is a simple and efficient way to determine if an element is in a list.

my_list = [1, 2, 3, 4, 5]
value_to_check = 3
if value_to_check in my_list:
print(f"Value {value_to_check} exists in the list.")
else:
print(f"Value {value_to_check} does not exist in the list.")

How Do You Check if a Key Exists and is Not None in Python?

To check if a key exists in a dictionary and its associated value is not None, you can combine the in keyword with a direct comparison:

my_dict = {'a': 1, 'b': None}

key_to_check = 'b'
if key_to_check in my_dict and my_dict[key_to_check] is not None:
print(f"Key '{key_to_check}' exists and is not None.")
else:
print(f"Key '{key_to_check}' does not exist or is None.")



S

Smitha Dinesh Semwal

Check if a Given Key Already Exists in a Python Dictionary - GeeksforGeeks (1)

Improve

Next Article

Python | Check if given multiple keys exist in a dictionary

Please Login to comment...

Check if a Given Key Already Exists in a Python Dictionary - GeeksforGeeks (2024)
Top Articles
How to use silence to become a better mentor | CIM Content hub
What is DNS, and Why is it Important?
How To Fix Epson Printer Error Code 0x9e
Asist Liberty
Terrorist Usually Avoid Tourist Locations
El Paso Pet Craigslist
Paris 2024: Kellie Harrington has 'no more mountains' as double Olympic champion retires
Explore Tarot: Your Ultimate Tarot Cheat Sheet for Beginners
Kobold Beast Tribe Guide and Rewards
The Potter Enterprise from Coudersport, Pennsylvania
Aiken County government, school officials promote penny tax in North Augusta
Waive Upgrade Fee
Carter Joseph Hopf
2013 Chevy Cruze Coolant Hose Diagram
Urban Dictionary Fov
1Win - инновационное онлайн-казино и букмекерская контора
Craigslist Pets Sac
2021 Lexus IS for sale - Richardson, TX - craigslist
Craiglist Galveston
Magic Mike's Last Dance Showtimes Near Marcus Cedar Creek Cinema
Dr Adj Redist Cadv Prin Amex Charge
Soccer Zone Discount Code
Vipleaguenba
MyCase Pricing | Start Your 10-Day Free Trial Today
2487872771
What Individuals Need to Know When Raising Money for a Charitable Cause
Kohls Lufkin Tx
Soul Eater Resonance Wavelength Tier List
Preggophili
O'reilly's In Monroe Georgia
Lcsc Skyward
Paradise Point Animal Hospital With Veterinarians On-The-Go
Srjc.book Store
Revelry Room Seattle
Amazing Lash Bay Colony
Isablove
FREE Houses! All You Have to Do Is Move Them. - CIRCA Old Houses
Ket2 Schedule
Bismarck Mandan Mugshots
Gets Less Antsy Crossword Clue
8 Ball Pool Unblocked Cool Math Games
Gt500 Forums
Immobiliare di Felice| Appartamento | Appartamento in vendita Porto San
Directions To Cvs Pharmacy
8776725837
Poe Self Chill
Strange World Showtimes Near Century Stadium 25 And Xd
Csgold Uva
3367164101
Kushfly Promo Code
Bbwcumdreams
Latest Posts
Article information

Author: Virgilio Hermann JD

Last Updated:

Views: 5794

Rating: 4 / 5 (61 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Virgilio Hermann JD

Birthday: 1997-12-21

Address: 6946 Schoen Cove, Sipesshire, MO 55944

Phone: +3763365785260

Job: Accounting Engineer

Hobby: Web surfing, Rafting, Dowsing, Stand-up comedy, Ghost hunting, Swimming, Amateur radio

Introduction: My name is Virgilio Hermann JD, I am a fine, gifted, beautiful, encouraging, kind, talented, zealous person who loves writing and wants to share my knowledge and understanding with you.