Level 1 The smallest value of one field
A tiny database holds records. A record is a dict from a field name (a string) to an integer value. Records don't all have the same fields: one may have "age" and "score", the next only "score".
Write min_by_key(records, key) -> dict: return the record with the smallest value for the field key.
- A record that doesn't have
keycounts as having the value0for it. - If several records share the smallest value, return the one that comes first in
records. - Return the record itself (or an equal dict). Don't change
recordsor any record in it.
records always holds at least one record.
records = [{"a": 3, "b": 1}, {"a": -2}, {"b": 5}]
min_by_key(records, "a") # {"a": -2}
min_by_key(records, "b") # {"a": -2}: it has no "b", so it counts as 0, which beats 1 and 5
min_by_key(records, "c") # {"a": 3, "b": 1}: every record counts as 0, so the first one wins
Constraints: up to 10^5 records with up to 10 fields each. Values are between -10^9 and 10^9. Field names are 1 to 10 lowercase letters.
Later levels add more ways to compare records, so keep the comparison in one place.
⭐ Bonus: a speed test with 30,000 records earns a star. One pass over the records is enough; you don't need to sort.