COGNITION FOUNDRYLEARN. BUILD. UNDERSTAND.
PY-012 / Give values useful names◷ 20 min read + practice

Dictionaries and keyed data

A list answers “which position?”. A dictionary answers “which name?”. When a piece of information has a meaningful label, a dictionary can make the code easier to read and maintain.

By the end, you can: Create a dictionary, read and update keys, use get() for optional values and iterate with items().
Before this lesson: PY-011

Model a record with keys

Curly braces create a dictionary: person = {"name": "Ada", "active": True}. Here "name" and "active" are keys, while the data to their right are values.

person["name"] retrieves the value associated with that key. A missing key raises KeyError. Dictionaries preserve insertion order in modern Python, but their purpose is lookup by key, not indexing by numeric position.

Update and add fields

person["city"] = "London" adds a new key. Assigning another value to an existing key replaces its old value. Keys must be hashable (for example, strings and integers); a list cannot be used as a dictionary key.

Keep keys consistent and meaningful. In a larger application, a misspelling such as "adress" versus "address" becomes a different key, not an automatic correction.

Handle optional fields safely

person.get("email", "Not provided") returns a fallback value when the key does not exist. "email" in person tests whether the key is present.

The default is used only when the key is missing, not when a stored value is an empty string. Decide whether “missing”, “empty” and “unknown” mean different things for the data you are processing.

Loop through keys and values

for key, value in record.items(): provides both pieces of each entry. For simple reports, this makes it easy to print a named field and its value without hard-coding every key.

Nested structures combine lists and dictionaries, such as a list of product records. We will practise those after developing reusable functions and input validation.

Try it yourself.

Choose a starting example or write something completely different. You control the code; the Run button executes what is in the editor, not a hidden preset.

CF Python PlaygroundBrowser-based Python
Ready to load Python
A simple record

Use descriptive keys to represent related facts.

Syntax colours highlight Python code. Tab inserts four spaces; press Escape then Tab to leave the editor. Ctrl+Enter runs the current code.
OUTPUT / ERRORS
Press Run Python to execute the editable code.
NOW MAKE IT YOURS

Add an author key and print its value.

Need a hint?

New entries use a quoted key followed by a colon and value.

On first Run, a pinned Python runtime downloads from jsDelivr. Code executes locally in your browser's Web Worker, not on our server. It cannot inspect your normal PC files or Windows hardware. Avoid entering secrets. Heavy/infinite loops are stopped by a time limit.

Check your understanding.

Try answering each question before opening its reference answer. Explain the idea aloud or change an example to test it for yourself.

  1. When would a dictionary be clearer than a list?

    View answer

    Choose a dictionary when values are naturally identified by names, such as "driver_version", "device_name" or "status". A list is better suited to a sequence of similarly positioned items. With a dictionary, readers can understand record["status"] without remembering a numeric index such as record[2].

  2. Why might settings.get("language", "system") be safer than settings["language"]?

    View answer

    Indexing with square brackets expects the key to exist and raises KeyError if it does not. get() lets you provide a fallback for an optional field so code can continue safely. You should still decide whether missing values are acceptable; when a field is mandatory, a clear error can be more appropriate than a silent fallback.

Where this leads.

With decisions, loops, lists and dictionaries covered, the next sequence can turn repeated operations into reusable functions with arguments and return values.