"""Reproduce acquisition sums from published analytical inputs. Python standard library. Source: Istat 2024 Table 17, CC BY 4.0; selection/calculations: Alisson Bento. """ from pathlib import Path import csv,json from decimal import Decimal as D p=Path(__file__).resolve().parent rows=list(csv.DictReader((p/'all-categories.csv').open(encoding='utf-8',newline=''))) out=[] ages=list(dict.fromkeys(r['age'] for r in rows if r['sex']=='all')) for age in ages: r=[r for r in rows if r['sex']=='all' and r['age']==age] assert len(r)==15 purchase=sum(D(v['percent']) for v in r if v['route'].startswith('bought_') and v['percent']!='-') other=sum(D(v['percent']) for v in r if not v['route'].startswith('bought_') and v['percent']!='-') out.append(dict(age=age,purchase_routes_sum_pct=str(purchase),other_reported_routes_sum_pct=str(other),unallocated_residual_pct=str(D(100)-purchase-other))) assert len(rows)==585 primary={r['age']:D(r['purchase_routes_sum_pct']) for r in out} assert primary['35 - 44']-primary['75 e più']==D('19.5') print(json.dumps(out,ensure_ascii=False,indent=2))