Dictionaries
As programs grow beyond toy examples, we need better ways to represent structured information. Lists are useful when order matters, but many real programs revolve around lookup: given a name, an identifier, or a label, we want to quickly find the associated data. Dictionaries exist in the syllabus because they support this style of thinking, which shows up constantly in data-driven programs and AI-adjacent systems.
What a dictionary is and when to use one
A dictionary is a collection that maps keys to values. Instead of accessing data by position, we access it by meaning. We choose dictionaries when each piece of data has a natural label and when order is less important than association.
This makes dictionaries a natural fit for representing things like attributes of an object, configuration values, or structured records loaded from data files.
Creating dictionaries with literal syntax
We create dictionaries using curly braces, with each key paired to a value using a colon. Commas separate each key–value pair.
planet = {
"name": "Mars",
"radius_km": 3389,
"has_rings": False
}
Keys are often strings, but the values can be any Python type. What matters is that each key uniquely identifies its value within the dictionary.
Accessing values by key
To retrieve a value, we use the key inside square brackets. This tells Python exactly which piece of data we want.
planet_name = planet["name"]
radius = planet["radius_km"]
This style of access reinforces the idea that dictionaries are about meaning, not position.
Adding, updating, and removing key–value pairs
Dictionaries are mutable, which means we can change them after creation. Assigning to a new key adds data. Assigning to an existing key updates it.
planet["moons"] = 2
planet["radius_km"] = 3390
We can also remove entries when they are no longer needed.
del planet["has_rings"]
This flexibility makes dictionaries useful for representing state that evolves as a program runs.
Using dictionaries to represent structured data
A dictionary can act as a simple data structure, grouping related values together under clear labels. This is especially common when modeling real-world entities or when preparing data for output.
planet = {
"name": "Jupiter",
"moons": ["Io", "Europa", "Ganymede", "Callisto"],
"type": "gas giant"
}
Seen this way, a dictionary becomes a lightweight way to express structure without defining new types or classes.
Conclusion
Dictionaries give us a way to organize data around meaning instead of position. We can create them easily, access values directly by key, and update their contents as our program runs. At this point, we are oriented to when dictionaries are the right tool and what they look like in real Python code.