Ravindra Bagale · Data Scienceसर्व coursesया course चे lessonsशोधाEnglish

Data Science · मराठी आवृत्ती · Python basics

P13.5 Python Project 5: Multi-Currency Sales Report JSON मध्ये Save करा

By Ravindra Bagale

हे का शिकायचं?

Functions, dictionaries, rounding आणि JSON एकत्र.

हे काय आहे?

वेगवेगळ्या currencies मधल्या sales rupees मध्ये बदलू, country नुसार total करू आणि JSON file मध्ये save करू.

कसं करायचं?

Step 1. Rates ची dictionary बनवा.

Step 2. प्रत्येक sale convert करा.

Step 3. Totals JSON मध्ये लिहा.

उदाहरणं: copy करा आणि चालवा

उदाहरण A: Convert, total आणि save

हा code चालवा:

import json
rates_to_usd = {"USD": 1.0, "GBP": 1.27, "EUR": 1.08, "INR": 0.012}
sales = [
    ("USA", 12000, "USD"), ("UK", 8000, "GBP"),
    ("Germany", 9500, "EUR"), ("India", 650000, "INR"), ("UK", 1500, "GBP"),
]
def to_usd(amount, cur):
    if cur not in rates_to_usd:
        raise ValueError(f"Unknown currency {cur}")
    return amount * rates_to_usd[cur]
by_country = {}
for country, amt, cur in sales:
    by_country[country] = round(by_country.get(country, 0) + to_usd(amt, cur), 2)
report = {"currency": "USD", "total": round(sum(by_country.values()), 2), "by_country": by_country}
with open("report.json", "w", encoding="utf-8") as f:
    json.dump(report, f, indent=2)
print(open("report.json", encoding="utf-8").read())

तुम्हाला दिसणारा output:

{
  "currency": "USD",
  "total": 42125.0,
  "by_country": {
    "USA": 12000.0,
    "UK": 12065.0,
    "Germany": 10260.0,
    "India": 7800.0
  }
}

याचा अर्थ: Report JSON मध्ये save झाला आणि परत वाचता आला.