compare approaches one problem · two ways
Compare Approaches
The same problem solved different ways in Python, run on the same input, with what really differs and when to use each.
Nested dicts vs dataclass models
Read earthquakes from GeoJSON and list the three strongest.
what differs
With dicts, every use repeats the JSON path (q["geometry"]["coordinates"][2]) and a missing key fails wherever it's first touched. A model converts and checks at the boundary, so later code is shorter and errors appear in one place.
at a glance
| approach | use it when |
|---|---|
| A · work with dicts | Quick scripts that touch a few fields once. |
| B · parse into dataclasses | Data used in several places: one function knows the JSON shape, the rest of the code uses typed attributes. |
Watch out: JSON numbers keep their written form: a magnitude of 6 arrives as the int 6, not 6.0, until something converts it (both print with :.1f here). Validation libraries such as pydantic go further; this runtime doesn't include pydantic, and a dataclass is often enough.
the outputs
Each approach runs on the same input.
concepts
parsing at the boundarydataclassesGeoJSON
learn it
Missing keys: get and safe defaults · Dataclasses: records without the boilerplate
related comparisons