Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Validate a record against required and optional fields

Create a robust validator that checks records against a simple schema, reporting errors and returning a cleaned record with defaults applied.

Python practice25 minError Handling & Edge CasesAdvancedLast updated March 20, 2026

Problem statement

You will write a function validate_record(record, schema) that validates a dictionary record against a simple schema specification. The schema is a dict mapping field names to a tuple: (expected_type, required_bool, default_value). Rules: - If record is not a dict, return (False, ['record must be a dict'], {}). - If schema is not a dict, return (False, ['schema must be a dict'], {}). - For each field in schema (in iteration order): - If a required field is missing, add an error "<field> is required". - If a field is present but its value is not an instance of expected_type, add an error "<field> expected <type_name>" and do NOT include it in the cleaned record. - If an optional field is missing, include the default_value in the cleaned record. - If a field is present and type checks, include it in the cleaned record. - If record contains keys not present in schema, add an error for each: "unexpected field: <key>". - Return a tuple: (is_valid, errors, cleaned_record) where is_valid is True when there are no errors, errors is a list of error messages in the order they were discovered, and cleaned_record is a dict containing only schema-defined fields (in schema iteration order) with provided or default values. Design your solution to be defensive, explicit about error messages and predictable in ordering so tests can compare the stringified return value.

Task

Implement validate_record(record, schema) to verify required fields, check types, apply defaults for optional fields, and report unexpected fields.

Examples

Valid record uses provided values

Input

validate_record({'name':'Alice','age':30},{'name':(str,True,None),'age':(int,False,0)})

Output

(True, [], {'name': 'Alice', 'age': 30})

Both fields are present and types match; no errors and cleaned record contains both values.

Input format

A call to validate_record(record, schema) where record is a dict and schema is a dict of field -> (type, required_bool, default).

Output format

A tuple (is_valid, errors, cleaned_record). The test harness will compare the stringified form.

Constraints

The schema must be a mapping of str -> (type, bool, any). Do not use external libraries. Preserve schema iteration order in the cleaned record.

Samples

Sample 1

Input

validate_record({'age':22},{'name':(str,True,None),'age':(int,False,0)})

Output

(False, ['name is required'], {'age': 22})

Missing required 'name' yields an error. 'age' is present and valid so it appears in the cleaned record.