Skip to content
Silver 5 min read · Wrangling 3 practice problems ↓

Wrangling data without pandas

Interviews often ask you to clean, join or summarise data in plain Python, without pandas or Spark. It shows you understand what those libraries do for you, and real pipelines need it in places where they are not available. This lesson works through parsing, flattening, deduplicating, joining and grouping by hand.

Foundations · Python for data engineers · Silver · Wrangling, lesson 1 of 1

Read first: Counter, defaultdict and deque · Generators and lazy evaluation (skip if you know them)

In plain words first

Think of the jobs Spark or SQL do with one line: split a log line into fields, unfold nested JSON into columns, keep the newest version of each record, join two lists, total per group. Each is a short loop over dicts and lists once you know the trick. This lesson is those tricks, one at a time.

Why wrangle without pandas?

Interviews ask for these in plain Python because they show you understand the algorithm behind the library call, and because real pipelines often need them where pandas is not available or the data does not fit: in a Lambda, an Airflow task or a streaming consumer. Every pattern below is something Spark or SQL does for you at scale.

Parsing with a regular expression

A compiled pattern with named groups reads every field at once, and anchoring with ^ and $ rejects lines that only partly match. re.fullmatch anchors both ends for you.

Python · payment lines into records
import re

PAY = re.compile(r"(?P<order>o\d+) paid (?P<amount>\d+(?:\.\d+)?) via (?P<method>\w+)")
lines = ["o12 paid 240.50 via upi", "o13 refunded 40", "o14 paid 99 via card"]
for line in lines:
    m = PAY.fullmatch(line)
    if m:
        print(m["order"], float(m["amount"]), m["method"])

Output from a real run

o12 240.5 upi
o14 99.0 card

Flattening JSON

Nested payloads become columns by joining the path to each leaf. A small recursiverecursion: A function that calls itself on a smaller part of the problem, with a base case that stops it. Learn more → helper does it; keep empty objects as values so a column does not appear and disappear with the data.

Python · a nested order into flat columns
def flat(node, prefix=""):
    if isinstance(node, dict) and node:
        for key, child in node.items():
            yield from flat(child, f"{prefix}.{key}" if prefix else key)
    else:
        yield prefix, node


order = {"id": "o9", "rider": {"name": "Kiran", "rating": 4.8}, "extras": {}}
print(dict(flat(order)))

Output from a real run

{'id': 'o9', 'rider.name': 'Kiran', 'rider.rating': 4.8, 'extras': {}}

Latest version per key

Change feeds send several versions of a row. One pass with a dict keeps the winner per key in O(n). Decide ties explicitly; >= keeps the later of two versions with the same timestamp ("last write wins").

Python · the latest status of each order
changes = [
    ("o1", 3, "picked"), ("o2", 1, "placed"),
    ("o1", 5, "delivered"), ("o1", 4, "on the way"),
]
latest_of = {}
for order_id, version, status in changes:
    seen = latest_of.get(order_id)
    if seen is None or version >= seen[0]:
        latest_of[order_id] = (version, status)
print({k: v[1] for k, v in sorted(latest_of.items())})

Output from a real run

{'o1': 'delivered', 'o2': 'placed'}

A hash join

Index the smaller side by key once, then probe it for every row of the other side: O(n + m) instead of a nested loop's O(n × m). This is the same algorithm a database or Spark uses for a broadcast hashhash table: The structure behind dicts and sets: a value's hash picks its slot, so finding, adding or removing it takes about the same time however big the collection is. Learn more → join. Keep SQL's rule that a None key never matches.

Python · orders left-joined to restaurants
restaurants = [
    {"rid": "r1", "name": "Spice Hub"},
    {"rid": "r2", "name": "Tiffin Co"},
]
orders = [
    {"oid": "o1", "rid": "r2"},
    {"oid": "o2", "rid": None},
    {"oid": "o3", "rid": "r9"},
]

by_rid = {r["rid"]: r for r in restaurants}
for o in orders:
    match = by_rid.get(o["rid"]) if o["rid"] is not None else None
    print(o["oid"], match["name"] if match else None)

Output from a real run

o1 Tiffin Co
o2 None
o3 None

Group-bys and null semantics

SQL's aggregate rules are worth copying: count(*) counts rows, but avg, sum and max ignore nulls, and an average of no values is null rather than zero. Keep "rows seen" and "values seen" as separate counters.

Python · average tip per city, ignoring missing tips
from collections import defaultdict

tips = [("Pune", 20), ("Pune", None), ("Goa", None), ("Pune", 30)]
rows, values = defaultdict(int), defaultdict(list)
for city, tip in tips:
    rows[city] += 1
    if tip is not None:
        values[city].append(tip)
for city in rows:
    v = values[city]
    average = sum(v) / len(v) if v else None
    print(city, "| orders:", rows[city], "| average tip:", average)

Output from a real run

Pune | orders: 3 | average tip: 25.0
Goa | orders: 1 | average tip: None
Why this matters: At scale, the same steps run in Spark: from_json and explode to flatten, row_number() over a window to dedupe, a broadcast join for the small side. Knowing the plain-Python algorithm makes the distributed version easy to reason about.

Common mistakes

  • Splitting log lines on spaces — Messages with spaces or brackets break it. Use an anchored regex.
  • Nested-loop joins — O(n × m). Build a dict index on one side.
  • Treating None as 0 in averages — It drags the average down. Skip missing values, as SQL does.

Key takeaways

  • Anchored regexes with named groups parse records safely.
  • Flatten JSON by joining paths; keep empty containers.
  • Dedupe with one dict pass; choose the tie rule.
  • Hash joins are O(n + m); aggregates ignore None like SQL.

Interview prep

THE QUESTION

"Join two lists of dicts on a key, in plain Python, efficiently."

A hash join: build a dict from the join key to the matching rows of the smaller list (a list of rows per key if keys repeat), then loop over the other list and look each key up, emitting one output row per match, or one row with None columns for a left join with no match. It is O(n + m) time and O(m) memory. I skip None keys, as SQL does, and rename clashing columns with a suffix.

Avoid: "I would just use pandas". Fine in production, but the question tests whether you know the algorithm: show the hash join or the dict pass first.

Follow-ups · answer out loud, then open

Follow-up"How do you deduplicate records to the latest version of each key?"
One pass with a dict from key to the best record so far, replacing when the timestamp is greater (or equal, for last-write-wins). O(n). In SQL or Spark the same is row_number() over (partition by key order by ts desc) = 1.
Scenario"Bad rows keep crashing a nightly load. What would you change?"
Validate each row against a schema, route failures with all their error messages to a dead-letter location, and load the good rows. Alert on the dead-letter count, so bad data is visible and fixable without blocking the pipeline.
Trap"In a left join, None keys on both sides match each other."
Not in SQL semantics: NULL = NULL is not true, so rows with null keys never match. Skip None keys when building the hash index.

Check yourself

3 questions

Joining 100k orders to 1k restaurants: the right approach?

Show the answer

Index restaurants in a dict, probe per order. A hash join, O(n + m).

In SQL semantics, avg over [10, None, 20] is...

Show the answer

15. Nulls are ignored: (10 + 20) / 2.

Which keeps the later of two records with equal timestamps?

Show the answer

ts >= best. Replacing on equality lets the later one win.

Practise this

Problems that use this, graded on hidden tests

See all 6 problems →

Keep going

Up next · new module: Objects that behave like values · 7 min read
Dunder methods and abstract classes
Equality, ordering and hashing that agree, NotImplemented, and interfaces with abc.

Related lessons

Previous: Exceptions and context managers

Primary sources: re: regular expressions · json