Validation Methods
Key Existence Validation
Using in
Operator
user_data = {'username': 'john_doe', 'age': 30}
## Check if key exists
if 'username' in user_data:
print("Username found")
Using .get()
Method
## Safe key access with default value
email = user_data.get('email', 'No email provided')
Advanced Validation Techniques
Multiple Key Validation
required_keys = ['username', 'email', 'age']
def validate_dict(data, required_keys):
return all(key in data for key in required_keys)
## Example usage
is_valid = validate_dict(user_data, required_keys)
Type Checking for Keys
def validate_key_types(data):
return all(
isinstance(key, (str, int))
for key in data.keys()
)
Validation Strategies
graph TD
A[Dict Key Validation] --> B[Existence Check]
A --> C[Type Validation]
A --> D[Value Constraints]
A --> E[Custom Validation]
Comprehensive Validation Example
def strict_dict_validator(data):
validations = [
## Check required keys
all(key in data for key in ['name', 'age']),
## Type constraints
isinstance(data.get('name'), str),
isinstance(data.get('age'), int),
## Value range
0 < data.get('age', 0) < 120
]
return all(validations)
## LabEx recommended validation approach
user_profile = {'name': 'Alice', 'age': 28}
print(strict_dict_validator(user_profile)) ## True
Best Practices
Validation Method |
Pros |
Cons |
in Operator |
Simple, readable |
No type checking |
.get() |
Safe access |
Limited validation |
Custom Functions |
Flexible, comprehensive |
More complex |