How to Validate Required Dict Keys in Python

Check whether a dictionary contains all required keys and return the list of missing ones using a simple list comprehension.

Easy Python 3.9+ Aug 9, 2026 Dictionaries & sets 12 views 0 copies

Python code

20 lines
Python 3.9+
def find_missing_keys(data: dict, required_keys: list) -> list:
    """Return a list of required keys that are missing from the dictionary."""
    return [key for key in required_keys if key not in data]


if __name__ == "__main__":
    user_data = {
        "name": "Alice",
        "email": "alice@example.com",
        "age": 30,
    }
    
    required = ["name", "email", "age", "phone", "address"]
    
    missing = find_missing_keys(user_data, required)
    
    if missing:
        print(f"Missing keys: {missing}")
    else:
        print("All required keys are present")

Output

stdout
Missing keys: ['phone', 'address']

How it works

The find_missing_keys function uses a list comprehension that iterates over required_keys and includes any key that is not present in the dictionary (key not in data). Because dictionary membership checks are hash-based, each lookup is O(1) on average, making the overall complexity O(n) where n is the number of required keys. The function returns a list of missing keys, which the caller can then check — if the list is empty, all required keys are present. This approach is clean, readable, and avoids manual loops with explicit appends.

Common mistakes

  • Using `key in data.keys()` instead of `key in data` — both work but the direct form is more idiomatic.
  • Forgetting that the function returns a list, not a boolean; you must check if the list is empty to know if validation passed.
  • Assuming the dictionary is guaranteed non-None; passing `None` will raise a TypeError.

Variations

  1. Use a set difference: `set(required_keys) - set(data.keys())` to get missing keys as a set.
  2. Add a default value with `dict.get(key, default)` when you want to fill missing keys with a placeholder.

Real-world use cases

  • Validating required fields in an API request body before processing or storing the data.
  • Checking that all mandatory configuration keys are present in a settings dictionary at application startup.
  • Verifying that a database row or webhook payload includes all expected columns before accessing them.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.