def create_utility_entries(utility_name, entries):
"""
Creates a nested structure of utility entries with defensive checks.
Args:
utility_name (str): The name of the utility.
entries (list): A list of entry dictionaries. Each entry should be a dictionary
with keys like 'id', 'description', 'value', etc.
Returns:
dict: A dictionary representing the utility structure. Returns None if invalid input.
Raises:
TypeError: if utility_name is not a string or entries is not a list.
ValueError: if entries contains elements that are not dictionaries.
"""
if not isinstance(utility_name, str):
raise TypeError("utility_name must be a string.")
if not isinstance(entries, list):
raise TypeError("entries must be a list.")
utility_data = {
"name": utility_name,
"entries": []
}
for entry in entries:
if not isinstance(entry, dict):
raise ValueError("All entries in the list must be dictionaries.")
# Defensive check for required keys (customize as needed)
if 'id' not in entry or 'description' not in entry:
print(f"Warning: Skipping entry due to missing 'id' or 'description': {entry}")
continue # Skip this entry
utility_data["entries"].append(entry)
return utility_data
if __name__ == '__main__':
# Example Usage:
try:
utility = create_utility_entries("Local Power", [
{"id": 1, "description": "Electricity Usage", "value": 1200},
{"id": 2, "description": "Water Consumption", "value": 500},
{"id": 3, "description": "Gas Usage", "value": 300},
{"description": "Missing ID", "value": 100} #Example of missing id
])
if utility:
print(utility)
except (TypeError, ValueError) as e:
print(f"Error: {e}")
Add your comment