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.
Python code
20 linesdef 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
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
- Use a set difference: `set(required_keys) - set(data.keys())` to get missing keys as a set.
- 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
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build a defaultdict histogram of categories in Python easy
- Build adjacency dict graph from edges in Python easy
- Build an OrderedDict insertion order demo in Python 3 easy
- Check Invertible Mapping for Duplicate Values in Python easy
- Compare Two Dictionaries in Python easy
Keep learning
Related tutorials and quizzes for this topic.