0
0
PythonHow-ToBeginner · 3 min read

How to Check if Key Exists in Dictionary Python

To check if a key exists in a Python dictionary, use the in keyword like key in dictionary. It returns True if the key is present, otherwise False.
📐

Syntax

Use the in keyword to check if a key exists in a dictionary.

  • key: The key you want to check.
  • dictionary: The dictionary to search in.
  • The expression key in dictionary returns True if the key is found, otherwise False.
python
key in dictionary
💻

Example

This example shows how to check if a key exists in a dictionary and print a message based on the result.

python
my_dict = {'apple': 1, 'banana': 2, 'cherry': 3}

if 'banana' in my_dict:
    print('Key "banana" exists in the dictionary.')
else:
    print('Key "banana" does not exist in the dictionary.')

if 'orange' in my_dict:
    print('Key "orange" exists in the dictionary.')
else:
    print('Key "orange" does not exist in the dictionary.')
Output
Key "banana" exists in the dictionary. Key "orange" does not exist in the dictionary.
⚠️

Common Pitfalls

Some common mistakes when checking for keys in dictionaries include:

  • Using dictionary[key] directly without checking if the key exists, which causes an error if the key is missing.
  • Confusing keys with values; in checks keys, not values.
  • Using get() method without a default value can return None for missing keys, which might be misleading.
python
my_dict = {'a': 1, 'b': 2}

# Wrong: This raises KeyError if key is missing
# print(my_dict['c'])

# Right: Check key before accessing
if 'c' in my_dict:
    print(my_dict['c'])
else:
    print('Key "c" not found.')
Output
Key "c" not found.
📊

Quick Reference

OperationSyntaxDescription
Check if key existskey in dictionaryReturns True if key is in dictionary, else False
Access value safelydictionary.get(key, default)Returns value if key exists, else default (None if not set)
Raise error if missingdictionary[key]Access value directly; raises KeyError if key missing

Key Takeaways

Use key in dictionary to check if a key exists safely and simply.
Avoid accessing dictionary keys directly without checking to prevent errors.
Remember that in checks keys, not values.
Use dictionary.get(key, default) to get values with a fallback.
Checking keys first helps write error-free and clear code.