1.2.24 · D3Introduction to Programming (Python)

Worked examples — Dictionaries — key-value pairs, access, methods (keys, values, items, get, update)

2,539 words12 min readBack to topic

This page is a firing range: every kind of situation a dictionary can throw at you, worked out one by one. If you have not yet met the basics, read the parent Dictionaries topic note first — here we assume you know that a dictionary is a set of {key: value} pairs and we drill every edge case.

Before anything else, one plain-words reminder so no symbol sneaks in unearned:


The scenario matrix

Think of every dictionary operation as landing in one cell of this grid. Our goal: hit every cell with at least one worked example.

# Case class What makes it tricky Example that hits it
C1 Key present — plain read The happy path Ex 1
C2 Key absent — bracket vs .get() Crash vs graceful Ex 2
C3 Create vs overwrite Same syntax, opposite effect Ex 3
C4 Empty dictionary {} Degenerate / zero input Ex 4
C5 Merging with update — shared keys Who wins the collision? Ex 5
C6 Illegal key — list/mutable TypeError, and the fix Ex 6
C7 Counting / accumulating (.get default trick) The 80% real-world loop Ex 7
C8 Iterating keys vs values vs items The classic wrong-loop bug Ex 8
C9 Real-world word problem Model reality as a dict Ex 9
C10 Exam twist — nested + view liveness Views are live, not copies Ex 10

Below, each example names the cell it covers. Figures appear where geometry/structure helps you see what the machine does.

Figure — Dictionaries — key-value pairs, access, methods (keys, values, items, get, update)

The figure above is the mental model for every example: a key goes through hash(), that number points at a slot, the slot holds the value. Keep this picture in mind — "absent key" just means the slot is empty.


Ex 1 — C1: the happy read


Ex 2 — C2: absent key, bracket vs .get()


Ex 3 — C3: create versus overwrite (identical syntax, opposite effect)


Ex 4 — C4: the empty dictionary (degenerate / zero input)


Ex 5 — C5: merging with update, and who wins a collision


Ex 6 — C6: an illegal key, and the tuple fix


Ex 7 — C7: counting with the .get default trick (the everyday power move)


Ex 8 — C8: iterating — keys vs values vs items


Ex 9 — C9: real-world word problem


Ex 10 — C10: the exam twist — nested dicts and live views


Recall Which cell does each example cover?

Ex 1 present-read ::: C1 Ex 2 absent key bracket vs get ::: C2 Ex 3 create vs overwrite ::: C3 Ex 4 empty dict methods ::: C4 Ex 5 update collision winner ::: C5 Ex 6 list key TypeError + tuple fix ::: C6 Ex 7 counting with get default ::: C7 Ex 8 keys vs values vs items ::: C8 Ex 9 canteen word problem ::: C9 Ex 10 nested + live views ::: C10


Connections

  • Parent topic (Hinglish)
  • Lists — ordered mutable sequences
  • Tuples — immutable sequences
  • Sets — unique hashable elements
  • Hashing and Hash Tables
  • For loops and iteration
  • Big-O Notation — time complexity