Group-by on CSV text without pandas

Python data engineering interview problem. Difficulty: intermediate. Pattern: Dictionaries. About 16 minutes. Part of the Pro drill bank.

Average an amount per region from CSV text using only the csv module, counting bad rows instead of failing. Treat this as a production helper: match the contracted return shape, including empty and duplicate inputs.

A small ingestion job receives CSV text and must report regional averages while counting bad rows for data-quality monitoring. Use Python's csv module to parse the header and rows. Trim region names, accept finite numeric amounts, average each region rounded to two decimals, and count invalid rows. Write avg_by_region(csv_text: str) -> tuple. The quoted Asia, East field is one region with amount 10, while EU has 5 and 15, giving averages 10.0 and 10.0 with zero bad rows. The starter file already contains the function name, harness and print lines. Keep them and fill only the function body.

Requirements

  • Use the standard csv module, not pandas.
  • Return (averages, bad_rows).
  • Skip blank lines, count other invalid rows and sort regions.

Constraints

  • A valid data row has exactly 2 fields and a finite numeric amount.
  • The return type is a tuple containing a dict and an integer.

Examples

Input: avg_by_region("region,amount\n\"Asia, East\",10\nEU,5\nEU,15\n") Output: ({'Asia, East': 10.0, 'EU': 10.0}, 0) The quoted region keeps its comma. EU averages 5 and 15 to 10.0.

Topics: lakebench, python, csv, group by, bad rows.

More Python interview questions · All interview problems · Learn data engineering

intermediate

Group-by on CSV text without pandas

Interview-style drill: Average an amount per region from CSV text using only the csv module, counting bad rows instead of failing.

Implement `avg_by_region(csv_text: str) -> tuple`. `csv_text` has a header line `region,amount` followed by data rows. Use only the standard library `csv` module, not pandas. Return `(averages, bad_rows)`: - `averages`: dict of region to the mean `amount`, rounded to 2 decimals, regions sorted by name - `bad_rows`: how many rows could not be used A row is **bad** when it does not have exactly 2 fields, its region is blank, or its amount is not a finite number. Bad rows are counted, never raised. Completely blank lines are skipped and are not counted. Regions are matched after trimming spaces.