1.2.26Introduction to Programming (Python)

Nested data structures — list of dicts, dict of lists

1,987 words9 min readdifficulty · medium

WHAT are they?

Figure — Nested data structures — list of dicts, dict of lists

HOW do you access data? (derive the indexing from scratch)

You always peel outer container first, then inner.

List of dicts — outer is a list (use integer index), inner is a dict (use key):

students[0]            # → {"name": "Asha", "age": 20, "marks": 88}   (whole row 0)
students[0]["name"]    # → "Asha"   : list-index 0, THEN dict-key "name"

Why this order? Because the value of students[0] is itself a dict, so the next [...] is a dict lookup, not a list index.

Dict of lists — outer is a dict (use key), inner is a list (use integer index):

students["name"]       # → ["Asha", "Ravi", "Meera"]   (whole column)
students["name"][0]    # → "Asha"   : dict-key "name", THEN list-index 0

WHY pick one over the other?

Task Best structure Reason
Add/remove a whole record List of dicts append one self-contained dict
Loop over records (for s in ...) List of dicts each item already a full row
Compute column average / max Dict of lists column is already a flat list
Memory of repeated keys Dict of lists keys stored once, not per row
JSON from an API List of dicts matches typical JSON arrays of objects

Worked examples


Common mistakes (steel-manned)


Flashcards

In a list of dicts, what does students[2]["age"] mean?
Take the dict at list index 2 (3rd record), then read its "age" field.
In a dict of lists, how do you get the same (row 2, age) cell?
students["age"][2] — key first, then index. Indices are swapped vs LoD.
Why is dict-of-lists faster for a column average?
The column is already a flat list, so sum(...) works directly — no gathering across records.
Why is list-of-dicts natural for adding a record?
Each record is a self-contained dict you can just append to the list.
LoD→DoL one-liner?
{k: [row[k] for row in lod] for k in lod[0]}
Error from students["name"] on a list of dicts?
TypeError — a list can't be indexed by a string key.
Why does dict.fromkeys(cols, []) cause bugs?
All keys share ONE list object; mutating one mutates all. Use {c: [] for c in cols}.
What's the relationship between LoD and DoL?
Transposes — same data, rows↔columns; indices swap order.

Recall Feynman: explain to a 12-year-old

Imagine a class register. List of dicts is like having one index card per student — each card says name, age, marks. Easy to add a new student (new card) or read one kid's whole card. Dict of lists is like keeping separate columns: one long list of all names, one long list of all ages, one of all marks. Easy to add up everyone's marks because they're already in a single line. Same kids, just stored sideways. To find one fact you pick a card and a line — in one you say "card 3, the marks part"; in the other you say "the marks column, the 3rd line".

Connections

  • Lists — the ordered outer container of LoD / inner of DoL
  • Dictionaries — key→value mapping powering both
  • List Comprehensions — the engine for LoD↔DoL conversion
  • JSON and APIs — real-world source of list-of-dicts
  • Pandas DataFrame — a turbocharged dict-of-lists (columns)
  • Loops and Iteration — traversing nested containers
  • Mutable vs Immutable — why shared-list bug bites

Concept Map

models

approach A

approach B

transpose of

each item is

each value is

access

access

indices swap

best for

best for

Nested data structures

Spreadsheet rows and columns

List of dicts

Dict of lists

Row record dict

Column list

students[i][c]

students[c][i]

Add records, loop, JSON

Column stats, less key memory

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, real-world data hamesha table jaisa hota hai — rows aur columns. Python mein isko store karne ke do tareeke hain. List of dicts matlab ek list jisme har element ek dictionary (ek poora row/record). Jaise ek student ki saari info ek card pe. Dict of lists matlab ek dictionary jisme har key ek column hai aur uski value ek list (us column ke saare values). Same data, bas 90 degree ghuma diya — yeh dono ek doosre ke transpose hote hain.

Access karte waqt rule simple hai: bahar wala container pehle, andar wala baad mein. List of dicts mein bahar list hai toh pehle integer index students[0], fir andar dict hai toh key students[0]["name"]. Dict of lists mein ulta — pehle key students["name"], fir index students["name"][0]. Dhyaan do, indices ka order swap ho jaata hai: [i][c] ban jaata hai [c][i]. Yahi transpose ka magic hai.

Kaunsa use karein? Agar tumhe naye record add karne hain ya har row pe loop chalana hai — list of dicts best, kyunki har record self-contained dict hai. Agar tumhe poore column ka average ya max nikalna hai — dict of lists best, kyunki column already ek flat list hai, seedha sum(...) chalao. API se JSON aata hai toh aksar list-of-dicts format mein hi aata hai.

Ek common galti: list of dicts pe students["name"] likhna — yeh TypeError dega kyunki list ko string se index nahi kar sakte, pehle integer chahiye. Doosri galti: dict.fromkeys(cols, []) se DoL banana — saari keys ek hi list ko point karti hain, ek mein append karo toh sab badal jaate hain. Iske jagah {c: [] for c in cols} use karo taaki har key ki apni fresh list ho.

Go deeper — visual, from zero

Test yourself — Introduction to Programming (Python)

Connections