"""Print a dict of postcode → property IDs for a portfolio, sorted by group size. Edit PORTFOLIO_ID below, then hit Run. """ from __future__ import annotations # --------------------------------------------------------------------------- # CONFIG # --------------------------------------------------------------------------- PORTFOLIO_ID: int = 796 # --------------------------------------------------------------------------- import sys from collections import defaultdict from pathlib import Path _REPO_ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(_REPO_ROOT)) from sqlalchemy import text # noqa: E402 from scripts.e2e_common import ENV_PATH, build_engine, load_env # noqa: E402 load_env(ENV_PATH) engine = build_engine() with engine.connect() as conn: rows = conn.execute( text("SELECT id, postcode FROM property WHERE portfolio_id = :pid ORDER BY postcode, id"), {"pid": PORTFOLIO_ID}, ).fetchall() by_postcode: dict[str, list[int]] = defaultdict(list) for pid, postcode in rows: by_postcode[postcode or "UNKNOWN"].append(int(pid)) sorted_dict = dict(sorted(by_postcode.items(), key=lambda kv: len(kv[1]))) output_path = _REPO_ROOT / "scripts" / f"properties_by_postcode_{PORTFOLIO_ID}.txt" lines = [f"{postcode!r}: {ids}" for postcode, ids in sorted_dict.items()] lines.append( f"\nTotal postcodes: {len(sorted_dict)}, total properties: {sum(len(v) for v in sorted_dict.values())}" ) output_path.write_text("\n".join(lines), encoding="utf-8") print(f"Saved to {output_path}")