Modules/Python/ Key and Value

Dictionaries

When position is the wrong way to find something, name it instead. A dictionary looks values up by key.

A value under a name

Curly braces, and each entry is key: value. You reach in with the key rather than a number.


                        

The key that is not there

Square brackets raise on a missing key. get returns a default instead, which is often what you want.


                        

Looking things up

Keys are usually strings, but any immutable value works - a number or a tuple, never a list.
d["missing"] raises KeyError. d.get("missing") returns None, and d.get("missing", 0) returns your own fallback.
Assigning to a key that does not exist creates it. There is no separate "add" step.
Looping over a dictionary gives you the keys. Use .items() when you want key and value together.

Dictionaries: A Practical Guide

A lookup table, not a numbered row.

Quick Context

A list answers "what is at position 2?". A dictionary answers "what is stored under 'age'?". When the natural question is a name rather than a number, a dictionary is the right shape, and the lookup stays fast however many entries it holds.

Missing keys are a decision, not an accident

Reaching for a key that is absent raises KeyError, which is Python insisting you decide what should happen. get lets you say "if it is not there, use this instead" in one line, and reads better than checking first and then indexing.

Interactive Exploration Guide

  1. Run the first editor. Note that assigning to person["city"] - a key that did not exist - simply adds it, and the length goes from 3 to 4.
  2. Trigger a KeyError. Add print(person["email"]) to the second editor and run. Then change it to person.get("email") and watch it return None quietly instead.
  3. Read the loop output. The loop prints keys, and the value comes from indexing with that key.
  4. Swap in .items(). Change the loop to for key, value in person.items(): and print both directly - same result, less indexing.

Key Takeaway

A dictionary maps keys to values and is the right structure whenever you would otherwise be remembering which position meant what. Square brackets raise KeyError on a missing key; get() returns a default. Iterating gives keys, and .items() gives both halves at once.

Check yourself

0 of 3

Answer without scrolling back up.

  1. person = {"name": "Ada"}. What does person["age"] do?

  2. What does person.get("age", 0) return when there is no age key?

  3. Looping with `for x in person:` gives you:

Cheat sheet

Dictionaries

A list answers "what is at position 2?". A dictionary answers "what is stored under 'age'?". When the natural question is a name rather than a number, a dictionary is the right shape, and the lookup stays fast however many entries it holds.

PYTHON · vizlearn.in/python/dictionaries.html