Editor

Data Validation

Advanced · Write the code · from Build a Simple ETL Pipeline: Extract, Transform, Load

From the lesson: Step 2: Validate the Extracted Data

Data from the real world is messy. Emails might be missing, amounts might be negative, names could be empty strings. Before transforming data, you should validate it and flag any problems. Some issues are warnings (missing email), while others are errors (negative amount).

Read this part of the lesson

Write a function validate_records(records) that checks each record for:

1. name must not be empty or missing - if invalid, add to errors list.

2. amount must be a positive number - if invalid, add to errors list.

3. email should not be empty - if empty, add to warnings list.

Return a tuple: (valid_records, errors, warnings) where valid_records excludes records with errors (warnings are OK).

Test with sample data that includes at least one invalid record (empty name or negative amount). Print "Valid: N", "Errors: N", "Warnings: N".

def validate_records(records):
valid = []
errors = []
warnings = []
# Check each record
pass
return valid, errors, warnings
# Test data with some problems
test_data = [
{'id': 1, 'name': 'Alice Johnson', 'email': 'alice@example.com', 'amount': 150.00},
{'id': 2, 'name': '', 'email': 'bad@example.com', 'amount': 230.50},
{'id': 3, 'name': 'Charlie Brown', 'email': '', 'amount': 75.00},
{'id': 4, 'name': 'Diana Prince', 'email': 'diana@example.com', 'amount': -50.00},
{'id': 5, 'name': 'Eve Wilson', 'email': 'eve@example.com', 'amount': 180.25},
]
valid, errs, warns = validate_records(test_data)

More ETL Pipeline exercises

All Python exercises · 50 practice problems · Practical Projects quiz