Reading — step 1 of 8
Learn
Think about a phone book. You don't search it by position — you search by name: "What's Alice's number?" The name is the key, the number is the value. A Python dictionary (also called a dict) works exactly like this — it maps keys to values for instant lookup. No scanning a list, no sorting, no binary search. Behind the scenes, a dict uses a hash table — average-case O(1) access regardless of size.
Dicts are arguably the most useful data structure in Python. Counting word frequencies, caching computed results, mapping IDs to records, configuration options, JSON data — they all come back to dicts.
Creating dictionaries
A dict literal uses curly braces with key: value pairs separated by commas.
Accessing values
dict[key]— fast, but raisesKeyErrorif missing.dict.get(key)— returnsNoneif missing.dict.get(key, default)— returnsdefaultif missing.
Use .get() whenever the key MIGHT be missing and missing is OK.
Membership and length
Note: in checks keys, not values. To check values: "Alice" in student.values().
Adding, updating, removing
Iterating
Three ways, picked by what you need:
.items() gives you tuples — almost always what you want when working with both.
Key requirements
Dict keys must be hashable (immutable). Strings, ints, floats, tuples (of hashables), and frozenset work. Lists, sets, and dicts DO NOT — they're mutable.
Values can be anything. (Yes, even other dicts — you'll see this with JSON.)
Insertion order is preserved
Since Python 3.7, dicts remember insertion order:
This matters when you serialize to JSON or print results — predictable order.
Worked example: word frequency
The dict + counting pattern is everywhere:
The .get(word, 0) returns 0 for new words, then we add 1 and store. Idiomatic and concise.
(For heavy counting work, collections.Counter is even cleaner — covered in Dictionary Techniques.)
Common mistakes
d[key]for missing keys raisesKeyError. Use.get()orkey in dfirst.- Iterating with
.items()and forgetting unpacking:for x in d.items(): print(x[0])works butfor k, v in d.items()is cleaner. - Trying to use a list as a key:
d[[1,2]] = ...is TypeError. Use a tupled[(1,2)]. - Mutating a dict while iterating it: raises RuntimeError in modern Python. Iterate over
list(d)if you need to delete keys.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…