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
On this page
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.
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.
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").
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.
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.
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
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."
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?"
Scenario"Bad rows keep crashing a nightly load. What would you change?"
Trap"In a left join, None keys on both sides match each other."
Check yourself
3 questionsJoining 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
- Parse Log Lines into RecordsData wrangling Easy
- Flatten Nested JSONData wrangling Medium
- Keep the Latest Record per KeyData wrangling Medium
Keep going
Up next · new module: Objects that behave like values · 7 min readDunder methods and abstract classes
Equality, ordering and hashing that agree, NotImplemented, and interfaces with abc.
Related lessons
Counter, defaultdict and dequePython for data engineers · 5 min read
Big-O and performance for data engineers
Previous: Exceptions and context managers
Primary sources: re: regular expressions · json