Lesson 13 of 30
In progress
Dictionaries: values with names
Map keys to values, read them safely with get(), loop over items, and count occurrences without writing one branch per case.
A list answers "what is at position three". A dictionary answers "what is the price of the large shirt". Once data has labels rather than positions, a dictionary is the natural home.
What you will learn
- Create dictionaries and read values without crashing on missing keys.
- Add, update and delete entries.
- Loop over keys, values and pairs, and count occurrences.
Keys and values
A dictionary stores pairs. The key is the label, the value is the data, and both live inside curly braces.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
print(prices["medium"])
print(len(prices))
print("large" in prices)
Press Run to see the output.
Lookup by key is fast even in a large dictionary, because Python hashes the key instead of scanning. Keys must be immutable: strings, numbers and tuples work; lists do not. Values can be anything, including lists and other dictionaries.
The in operator checks keys, not values. "pens" in stock asks whether the label exists; to ask whether a count appears, you have to search stock.values(), which scans and is much slower.
Reading a missing key with square brackets raises KeyError. That is useful when the key must exist, and annoying when it might not. get() handles the second case.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
print(prices.get("small"))
print(prices.get("xlarge"))
print(prices.get("xlarge", 0))
Press Run to see the output.
get returns None when the key is absent, or the default you pass. Use get for optional data and square brackets when a missing key is a real bug you want to hear about.
Add, update, delete
Assignment adds a key that does not exist and overwrites one that does. del removes a pair, and pop removes it while returning the value.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
stock["erasers"] = 30
stock["pens"] = 35
print(stock)
removed = stock.pop("notebooks")
print(removed)
print(stock)
del stock["erasers"]
print(stock)
Press Run to see the output.
pop accepts a default too: stock.pop("markers", 0) avoids a KeyError when the key may be absent. update merges another dictionary into this one, which is handy for applying a batch of changes.
Values can themselves be dictionaries, which is how you model a record with sections. user["address"]["city"] reads the city from a nested address, and each bracket is one lookup. When a level may be missing, chain get calls with an empty dictionary as the default: user.get("address", {}).get("city", "Unknown"). That expression never raises, at the cost of hiding a structural problem you might prefer to see.
Looping over a dictionary
Iterating a dictionary gives keys by default. .keys(), .values() and .items() make the intent explicit, and .items() is what you usually want.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
for item in stock:
print(item)
for name, count in stock.items():
print(f"{name}: {count}")
Press Run to see the output.
Unpacking name, count from each pair is the idiom to learn. Since Python 3.7, dictionaries keep insertion order, so output is predictable; do not confuse that with sorting. To process keys in alphabetical order, loop over sorted(stock).
Counting is the killer feature
The pattern below replaces what would otherwise be a chain of if statements, one per possible value.
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
for word in words:
counts[word] = counts.get(word, 0) + 1
print(counts)
Press Run to see the output.
Read counts.get(word, 0) as "the current count, or zero if this is the first time". Then add one and store it back. That single line is worth memorising; it appears in word counts, vote tallies and inventory checks.
Changing a dictionary’s size while looping over it raises RuntimeError: dictionary changed size during iteration. Collect the keys to remove first, then delete them: for key in [k for k in stock if stock[k] == 0]: del stock[key]. The list comprehension takes a snapshot, so the loop is safe.
Count how many times each word appears in a sentence, ignoring case and punctuation, then print the three most common words. sorted with a key function gets you the ranking without importing anything.
Show solution
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.
for word in clean.split():
counts[word] = counts.get(word, 0) + 1
ranked = sorted(counts.items(), key=lambda pair: pair[1], reverse=True)
for word, count in ranked[:3]:
print(word, count)
Press Run to see the output.
split() breaks on whitespace, and stripping the full stop stops hot. becoming a separate key from hot. The lambda sorts by the count, not the word.
Recap
- Dictionaries map immutable keys to values, with fast lookup.
get(key, default)reads optional keys without raising;items()loops over pairs.counts[key] = counts.get(key, 0) + 1is the standard counting idiom.
Next, you will meet the two smaller collections: tuples for fixed records and sets for uniqueness.
Are dictionaries ordered?
Can a dictionary key be a tuple?
Progress is saved in this browser only. No account, no email.