Skip to chapter content
navan✳THE BUILD LABPYTHON / GUIDE
0/26 read
CHAPTER 07 / 26 · DATA AND TEXT

Dictionaries and structured records.

Name fields clearly, retrieve them safely, and choose keys that mean something.

BY NAVAN SAMI5 MIN READTHEORY FIRST
01 / THE BASICS

Start here.

A dictionary stores pairs of keys and values. The example {'name': 'Ada', 'age': 37} maps the key 'name' to the text 'Ada' and 'age' to the number 37. Curly braces create the dictionary; colons separate each key from its value. Unlike a list position, a key describes meaning. person['name'] asks for the value under that exact key. If the key is absent, square-bracket lookup raises KeyError.

The get method is useful when absence is expected. person.get('city', 'unknown') returns the city when present and the fallback 'unknown' otherwise. It does not add the fallback to the dictionary. Choose between [] and get according to the contract: a missing required field should usually be reported, while a genuinely optional field may have a default. A stored zero or empty string is still present, so a truthiness check is not the same as a key-existence check.

Dictionaries are mutable and preserve insertion order in modern Python, but their main strength is named lookup. for key, value in person.items(): visits the pairs. Keys need to be hashable, so strings and numbers work while lists do not. A set uses similar hashing to store unique values without associated values. When data comes from a file or network, describe which keys are required and what kind of value each should contain before relying on them.

02 / THE IDEA

Build the model.

A dictionary maps a key to a value. It is a natural way to represent a record with named fields, such as a person with a name and an age, or a lookup table keyed by identifier. Access with record['name'] when the field must exist; use record.get('name') when absence is an expected case and you have a sensible fallback.

Keys must be hashable, which usually means immutable values such as strings, numbers, or suitable tuples. A value can be any Python object. Dictionaries preserve insertion order in modern Python, but their main purpose is lookup by meaning rather than position. When you need a unique set of values without associated data, a set expresses that more directly.

03 / UNDER THE SURFACE

How it works.

A missing key raises KeyError with square-bracket access. That can be useful because it exposes a broken assumption; replacing every lookup with get may conceal missing required data. Iterate over .items() when you need each key-value pair, .keys() for names, and .values() for values. These views reflect the current dictionary rather than copying everything into a new list.

Nested dictionaries represent larger structures, but depth makes the shape harder to remember. Write down which fields are required and what types they hold, then validate data that comes from a file or network. A dataclass can later give a stable record shape a named type, while a dictionary remains useful for dynamic keys and JSON-shaped data.

04 / A WORKED EXAMPLE

Read it line by line.

example.py
person = {'name': 'Ada', 'age': 37}
print(person['name'])
print(person.get('city', 'unknown'))

The first lookup finds the required name and prints Ada. The second asks for city, which is not present, so get returns the supplied fallback 'unknown'. Nothing is added to person by get. If you used person['city'] instead, Python would raise KeyError.

05 / ANOTHER EXAMPLE

See the rule again.

example-2.py
words = ['red', 'blue', 'red']
counts = {}
for word in words:
    counts[word] = counts.get(word, 0) + 1
print(counts)

The result is {'red': 2, 'blue': 1}. get(word, 0) supplies zero for a word not seen yet; each pass adds one. This pattern turns a sequence into a frequency table without predeclaring every possible word.

06 / REMEMBER THIS

A mistake to avoid.

Do not test whether a required field exists with if record.get('count'): a present count of zero is falsy. Use 'count' in record or compare with None when zero is valid.

Finished this chapter?
Built with curiosity. By Navan Sami. ↗Python · Understand the idea, then write the code.