▶ Sign up free for the video, slides & prompts
The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.
Checking…
Dictionaries
Look things up by key: phone books, prices and settings.
🎬 Video version coming soon — read it now
A dictionary (dict) stores key → value pairs. Instead of looking things up by position, you look them up by name, like a phone book.
Adding, changing and removing
Keys must be unique. Setting a key that already exists replaces its value.
Safe lookups
Asking for a key that doesn't exist gives a KeyError:
Looping over a dictionary
Counting with a dictionary
A classic task: how often does each word appear?
counts.get(w, 0) + 1 means "the current count, or 0 if it's new, plus one". You'll use this pattern constantly.
Values can be anything
{(17.69, 83.22): "Vizag"}, but lists don't, because keys must never change.In one line
A dictionary looks values up by key; use .get() for safe lookups and .items() to loop over pairs.
Share with a friend