Dictionaries as labelled records

A student, a SKU and a JSON payload share labelled fields. employee["pf"] survives last year’s Excel column shuffle. Missing keys are a policy, not a crash you ignore.

Student diary

Dictionaries label each field.

You will be able to

  • Store a record as labelled fields
  • Read and update by key
  • Pass a whole record into a function

Labels instead of column numbers

A student, a SKU and a JSON payload share labelled fields. employee["pf"] does not care that pf used to be column C. Missing keys: on a laptop .get("pf", 0) or KeyError. Here, only write keys you set. Looping for k in emp visits keys.

Other constructors on a laptop: dict(name="Diya"), dict([("a", 1)]). Python 3 views (keys/items) are lazy. You need one shape: a dict per row.

A row is a value you can pass

def pf_of(emp): return emp["pf"] takes the whole record. Fifty employees are a list of dicts — the in-memory CSV. Nested dicts (address inside student) exist; keep one level until you must nest.

Words that matter

Dictionary
A mapping from keys to values — one labelled record.
Key
The field name, usually a string.
JSON object
The on-the-wire twin of a dict.

Common mistakes

Avoid: employee[2] for PF because it was column C.

Do this: employee["pf"] so a new column cannot steal the meaning.

Run it step by step

Each box is a real program. Press Run, change a number, Run again — the output must follow your code.

1. Step 1 — read labelled fields

Change pf. The print follows the key.

Python sandboxlesson://workspace
console

Edit the example, press Run, then Build if you want a compile check.

build

Press Build to compile.

2. Step 2 — update a field

Transfer is one assignment.

Python sandboxlesson://workspace
console

Edit the example, press Run, then Build if you want a compile check.

build

Press Build to compile.

Example program — A function that takes a record

One argument, not three.

Python sandboxlesson://workspace
console

Edit the example, press Run, then Build if you want a compile check.

build

Press Build to compile.

Your turn — Read the lab id

sensor = {"id": "DHT-04", "c": 31}. Print so DHT-04 appears.

Python sandboxlesson://workspace
console

Edit the example, press Run, then Build if you want a compile check.

build

Press Build to compile.

Self-assessment

Check your understanding before you mark the lesson complete.

1. emp["dept"] reads a field from a…
2. A CSV row with a header is closest to…

Progress is stored in a browser cookie on this device.