Recursive Schema Validation
Trees & GraphsAuto-graded · 20 test casesLast updated
Tests recursive validation of nested dictionaries against a schema with type and presence requirements.
You are given a schema specification and a data dictionary. Your task is to determine whether the data conforms to the schema.
Schema Structure
A schema is a dictionary mapping field names to field specifications. Each specification contains:
"type": The expected type of the field's value. This can be:"string"for string values"int"for integer values- A nested dictionary (representing a sub-schema for nested objects)
"required": A boolean indicating whether the field must be present in the data
Validation Rules
- Required fields: If a field is marked
required: Trueand is absent from the data, validation fails. - Type matching: If a field is present in the data, its value must match the declared type:
- For
"string", the value must be a string - For
"int", the value must be an integer (not a boolean, even though booleans are technically integers in Python) - For a nested dictionary type, the value must be a dictionary that recursively validates against the nested schema
- For
- Optional fields: Fields marked
required: Falsemay be absent. If they are present, they must still match the declared type. - Extra fields: Fields present in the data but not defined in the schema are allowed and should be ignored.
Write a function that returns True if the data is valid according to the schema, and False otherwise.
Constraints
- The input data is always a dictionary
- Schema definitions form a tree structure with no circular references
- Type checking is limited to
"int","string", and nested dictionaries - Integer fields must be actual integers, not booleans or other numeric types
- A field is considered present if its key exists in the data dictionary, regardless of whether its value is
None
Examples
Example 1
Input: validate_data({'id': {'type': 'int', 'required': True}, 'metadata': {'type': {'source': {'type': 'string', 'required': True}}, 'required': False}}, {'id': 1, 'metadata': {'source': 'sensor_a'}})
Output: True
Example 2
Input: validate_data({'id': {'type': 'int', 'required': True}, 'metadata': {'type': {'source': {'type': 'string', 'required': True}}, 'required': False}}, {'id': 1, 'metadata': {}})
Output: False
Hints
Hint 1
Walk through the schema fields rather than the data fields to naturally handle extra data keys
Hint 2
For nested schemas, first verify the value is a dictionary before attempting recursive validation
Hint 3
Remember that in Python, bool is a subclass of int, so use exact type checking for integer fields
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution uses recursion to validate nested structures by traversing the schema tree. The key insight is to iterate through schema fields rather than data fields, which naturally handles extra keys in the data.
For each field defined in the schema:
- Check presence: If the field is missing from the data, fail only when it's required; otherwise skip it
- Check type: If the field exists, verify its value matches the expected type:
- For primitive types (
"string"or"int"), perform direct type checks - For nested schemas (dictionary types), verify the value is also a dictionary and recursively validate it against the nested schema
- Use exact type checking for integers (
type(value) is not int) to exclude booleans, sinceboolis a subclass ofintin Python
- For primitive types (
If all schema fields pass both checks, return True. Any violation returns False immediately.
Correctness
The algorithm is correct because it directly encodes the validation rules: a field must be present if required, and present fields must match their declared types. Recursion terminates because the schema is acyclic and each recursive call operates on a strictly smaller nested schema.
Critical implementation details:
- Using exact type checking for integers prevents accepting boolean values
- Checking
isinstance(value, dict)before recursing prevents runtime errors when a non-dict value is passed to the recursive call - Iterating over schema keys rather than data keys means extra data fields are never examined
Complexity
- Time: O(F), where F is the total number of field definitions across all levels of the schema. Each field is visited once, and dictionary lookups are O(1).
- Space: O(D) for the recursion call stack, where D is the maximum nesting depth of the schema.
from typing import Dict
def validate_data(schema: Dict, data: Dict) -> bool:
for field, definition in schema.items():
if field not in data:
if definition["required"]:
return False
continue
value = data[field]
expected = definition["type"]
if isinstance(expected, dict):
if not isinstance(value, dict) or not validate_data(expected, value):
return False
elif expected == "string":
if not isinstance(value, str):
return False
elif expected == "int":
if type(value) is not int:
return False
else:
return False
return True