Skip to content

How to Check If a Key Exists and Has a Value in Python Dictionary

Learn how to safely verify a dictionary key exists and contains a valid (non-None) value in Python using .get() or explicit in checks.

When working with Python dictionaries, a common requirement is to verify two things simultaneously: first, that a specific key exists to avoid a KeyError, and second, that the value associated with that key is valid (typically meaning not None).

This guide covers the standard "Look Before You Leap" approach using the in operator, the concise .get() method, and common pitfalls regarding "falsy" values like 0 or empty strings.

Understanding the Problem: Missing Keys vs. None Values

Accessing a missing key in a dictionary raises an error. However, a key might exist but carry a None value, which can cause logic errors if your code expects data.

data = {
    "user_id": 101,
    "session_token": None 
}

try:
    email = data['email']
except KeyError as e:
    print(f"Error: {e}")

token = data['session_token']
print(f"Token value: {token}") 

Output:

Error: 'email'
Token value: None

Method 1: Using the in Operator (Explicit Check)

The most explicit way to validate data is to first check for key membership using in, and then check if the value is not None.

data = {
    "user_id": 101,
    "session_token": None,
    "status": "active"
}

if "status" in data and data["status"] is not None:
    print(f"Status is valid: {data['status']}")
else:
    print("Status is missing or None")

if "session_token" in data and data["session_token"] is not None:
    print("Token found.")
else:
    print("Token is missing or None (Invalid).")

Output:

Status is valid: active
Token is missing or None (Invalid).

Method 2: Using .get() (Concise Approach)

The .get(key) method returns the value for a key if it exists, or None (by default) if it does not. This allows you to combine the existence check and the value check into a single expression.

If .get() returns None, it means either the key is missing or the value is explicitly None. In both cases, the data is usually considered "invalid" for processing.

data = {
    "user_id": 101,
    "session_token": None
}

user_id = data.get("user_id")

if user_id is not None:
    print(f"Valid User ID: {user_id}")

email = data.get("email") # Returns None automatically

if email is not None:
    print(f"Email: {email}")
else:
    print("Email is missing or None.")

Output:

Valid User ID: 101
Email is missing or None.

Common Pitfall: Truthiness vs. Not None

A common mistake is using implicit boolean checks (if data.get(key):) instead of checking for None explicitly. In Python, 0, False, and "" (empty string) evaluate to False.

If 0 is a valid value for your data (e.g., an account balance or index), a simple boolean check will incorrectly treat it as missing.

data = {
    "balance": 0,       # Valid value, but Falsy
    "username": "guest"
}

if data.get("balance"):
    print(f"Balance found: {data['balance']}")
else:
    print("Balance is missing or invalid (Incorrect result).")

if data.get("balance") is not None:
    print(f"Balance found: {data['balance']}")

Output:

Balance is missing or invalid (Incorrect result).
Balance found: 0

Conclusion

To ensure a dictionary key exists and contains a value:

  1. Use .get(key) is not None for the most concise, Pythonic solution. It handles missing keys gracefully.
  2. Use key in dict and dict[key] is not None if you prefer explicit steps or need to distinguish between a missing key and a None value.
  3. Avoid if dict.get(key): if your values might be numeric zeros or boolean False.
Navigation