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.

Easy Python 3.9+ Aug 9, 2026 Cloud + Python 14 views 0 copies

Python code

20 lines
Python 3.9+
def 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

stdout
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

  1. Return a breakdown dict `{service: cost}` instead of printing inside the loop, so callers can aggregate externally.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Cloud + Python

Related tutorials and quizzes for this topic.