How to Calculate Cloud Cost Estimates with a Python Dictionary
Mocks a cloud pricing calculator using a dictionary of service rates and computes total estimated cost for given service hours.
Python code
20 linesdef estimate_cost(service, hours, rate_table=None):
if rate_table is None:
rate_table = {
"basic": 50,
"standard": 75,
"premium": 100
}
if service not in rate_table:
raise ValueError(f"Unknown service: {service}")
return rate_table[service] * hours
if __name__ == "__main__":
services = {"basic": 10, "standard": 20, "premium": 15}
total_cost = 0
for service, hours in services.items():
cost = estimate_cost(service, hours)
print(f"{service}: {cost}")
total_cost += cost
print(f"Total: {total_cost}")
Output
basic: 500
standard: 1500
premium: 1500
Total: 3500
How it works
The estimate_cost function maps a service name to a fixed hourly rate stored in a dictionary. A None default argument allows the rate table to be defined once and reused across calls. Lookups are O(1) and the if guard raises a clear ValueError for unknown services. The script loops over a second dict of usage hours, applies the rate per service, and accumulates a total cost. This mirrors how simple cloud billing estimators combine rate cards with usage data before sending data to a real provider API.
Common mistakes
- Forgetting that the default rate table is only used when `rate_table` is `None`; passing an empty dict silently raises `ValueError`.
- Multiplying hours by a string rate from config that wasn't cast to `int` or `float`.
- Using mutable default arguments like `rate_table={...}` directly in the signature instead of the `None` pattern.
Variations
- Return a breakdown dict `{service: cost}` instead of printing inside the loop, so callers can aggregate externally.
- Add a `discount_percent` parameter to apply volume pricing or commit-based savings.
Real-world use cases
- Prototyping a billing estimator for a serverless app before wiring up a provider SDK like boto3.
- Unit-testing a cost calculation function with mock rate tables instead of live cloud APIs.
- Building a quick ad-hoc CLI to quote monthly spend from a spreadsheet of service hours.
Sponsored
More from Cloud + Python
- Build a URL Shortener Client with Python medium
- Create a Cloud Storage Helper Class in Python easy
- Create a Data Helper Class for Beginners in Python easy
- Cross Account Role Chaining Mock Credentials in Python medium
- Exponential Backoff with Jitter for Cloud API Calls in Python medium
- Generate Mock CloudFormation Stack Events in Python easy
Keep learning
Related tutorials and quizzes for this topic.