Cohort 4Register

PART 2 · PYTHON FOUNDATIONS · PRACTICE

Practice set 1: foundations

FreeLesson 32 of 78

Cover the solution, write your own, then compare outputs. Every answer reads the store files.

Q7Total amount and order count per status from orders.csv, without pandas.DEEASY

Approach: One pass, a dict of [count, total] per status.

import csv
from collections import defaultdict

stats = defaultdict(lambda: [0, 0.0])
for r in csv.DictReader(open("orders.csv")):
    s = stats[r["status"]]
    s[0] += 1
    s[1] += float(r["amount"])
for status, (n, total) in sorted(stats.items()):
    print(f"{status:<10} {n:>2} {total:>9.2f}")

Output

cancelled   2   3498.00
delivered  12  18972.00
returned    1    798.00

Q8Which customers in customers.json have never placed an order?DEEASY

Approach: Two sets of ids and a difference. O(n + m).

import csv, json

customers = json.load(open("customers.json"))
all_ids = {c["customer_id"] for c in customers}
ordered = {int(r["customer_id"])
           for r in csv.DictReader(open("orders.csv"))}
names = {c["customer_id"]: c["name"] for c in customers}
print([names[i] for i in sorted(all_ids - ordered)])

Output

['Zoya']

Q9Count events per device from events.jsonl. The device sits inside a nested props object.DEEASY

Approach: Stream the file, read the nested key safely, count with Counter.

import json
from collections import Counter

with open("events.jsonl") as f:
    devices = Counter(json.loads(line).get("props", {})
                      .get("device", "unknown") for line in f)
print(devices.most_common())

Output

[('mobile', 7), ('desktop', 4), ('tablet', 1)]

Q10Clean these amount strings into Decimal, skipping the ones that cannot be parsed: "₹1,198.00", " 796 ", "N/A",

"1,499.5". DE MEDIUM

Approach: Strip symbols and separators, try Decimal, catch only InvalidOperation.

from decimal import Decimal, InvalidOperation

raw = ["\u20b91,198.00", " 796 ", "N/A", "1,499.5"]
clean, rejected = [], []
for text in raw:
    t = text.replace("\u20b9", "").replace(",", "").strip()
    try:
        clean.append(Decimal(t))
    except InvalidOperation:
        rejected.append(text)
print(clean, rejected)

Output

[Decimal('1198.00'), Decimal('796'), Decimal('1499.5')] ['N/A']

Q11From employees.csv, find the second-highest distinct salary. Return None if it does not exist.DEMEDIUM

Approach: Set of salaries removes ties, sort descending, guard the index.

import csv

rows = csv.DictReader(open("employees.csv"))
salaries = {int(r["salary"]) for r in rows}
ordered = sorted(salaries, reverse=True)
second = ordered[1] if len(ordered) > 1 else None
print(second, ordered[:3])

Output

180000 [250000, 180000, 160000]

Practice before you move on

  1. Solve Q7 to Q11 in the Try it editor before you read each solution.
  2. Change Q9 to count events per event type instead of per device.