Python Dictionaries
Learn the labeled container: storing values under keys, safe lookup with get, adding and removing entries, and walking keys, values, and pairs.
Basic
A list answers the question what comes next. A dictionary answers the question what is the value for this label. Written in braces as pairs of key: value , it stores each value under a key you choose, a string, a number, a tuple, and hands it back the instant you present that key. Nearly every real program eventually holds data whose natural shape is name-and-value rather than position, and this is the container built for it.
Storing and fetching
|
|
Curly braces, colon pairs, and lookup by name.
Fetching with a missing key raises a
KeyError, which is loud and immediate. When absence is an expected state rather than a bug,
loaf.get("discount") returns
None quietly, and
loaf.get("discount", 0) returns a default you choose instead. The choice between brackets and
get is the choice between missing-as-mistake and missing-is-fine, and making it consciously is most of using dictionaries well.
Changing what is stored
Dictionaries are mutable like lists: assignment writes through. Assigning to an existing key replaces its value, assigning to a new key creates the entry on the spot, and
del removes a pair entirely. The
in operator asks about keys, not values, which is worth saying aloud once:
"price" in loaf is a question about labels.
|
|
Write, create, and delete, all through the key.
Walking the contents
A for loop over a dictionary walks its keys by default. The three views,
keys(),
values(), and
items(), let you choose what you actually want, and
items() with tuple unpacking is the idiom that makes dictionaries a pleasure to read.
|
|
Three views, and the one you will actually use.
Nesting: dictionaries of dictionaries
Values can be anything, including lists and other dictionaries, and that is how real records are built: a dictionary per loaf, a list of them for the menu, keys for the fields. Chained brackets reach in,
menu[0]["price"], and a loop over the list with
items() inside composes the two containers naturally. Start simple, one level at a time, and print as you go; nested data forgives everything except silence.
Run the bakery board
The example below keeps a menu in one dictionary and a day's orders in another, then reports on both. Run it, then exercise the edges: ask for a missing bread with brackets to meet the
KeyError in person, then switch to
get with a default and watch the program survive. Add a new bread to the menu mid-file and watch every later report pick it up without ceremony.
Output
Ready to run.
What to notice
The orders loop looked prices up in the other dictionary by key; the two containers worked as a pair without any index math.
Missing keys were handled twice, once with a default and once by construction, because every ordered bread existed in the menu.
Dictionary order matched the order entries were written and added, which Python has guaranteed since version 3.7.
Quick check
If you can choose between brackets and
get with a reason, iterate pairs with
items() without hesitating, and explain what
in asks a dictionary, labeled data is yours. Next, loops does the walking for everything so far. When you are ready, take the Python Dictionaries quiz.
Thanks for your feedback.
Mark this learning resource complete to track your learning progress.