Quick answerPractise Python dictionaries with six auto-checked exercises: a safe lookup with get(), counting letters, grouping words by first letter, inverting a dictionary, merging two score tables and reading nested data. The tests call your functions and compare the dictionaries they return.
Dictionary essentials
d = {"a": 1} creates one; d["b"] = 2 adds a key; d.get("z", 0) reads a key with a fallback instead of raising KeyError; for key, value in d.items(): loops over pairs. Since Python 3.7 dictionaries keep insertion order, but the tests here compare dictionaries with ==, which ignores order.
Exercises
1. Price lookupeasy
Write price(item) that returns the price from the PRICES dictionary, or 0 if the item isn't on the menu.
๐ก PRICES.get(item, 0) returns 0 when the key is missing.
Show solution
PRICES = {"coffee": 2.5, "tea": 2.0, "cake": 3.75}
def price(item):
return PRICES.get(item, 0)
Square-bracket lookup raises KeyError for missing keys; get lets you choose a default.
2. Letter frequencyeasy
Write letter_counts(word) returning a dictionary of how many times each letter appears. "hello" โ {'h': 1, 'e': 1, 'l': 2, 'o': 1}.
๐ก Same pattern as a word counter: counts[ch] = counts.get(ch, 0) + 1.
Show solution
def letter_counts(word):
counts = {}
for ch in word:
counts[ch] = counts.get(ch, 0) + 1
return counts
Counting with a dictionary is one of the most common patterns in Python; collections.Counter(word) is the built-in shortcut.
3. Group by first lettermedium
Write group_words(words) that returns a dictionary mapping each first letter to the list of words starting with it, in the original order.
๐ก groups.setdefault(w[0], []).append(w) creates the list the first time a letter appears.
Show solution
def group_words(words):
groups = {}
for w in words:
groups.setdefault(w[0], []).append(w)
return groups
setdefault returns the existing list, or inserts and returns a new empty one. collections.defaultdict(list) is the alternative.
4. Invert a dictionarymedium
Write invert(d) that swaps keys and values: {'a': 1, 'b': 2} โ {1: 'a', 2: 'b'}.
๐ก A dictionary comprehension: {v: k for k, v in d.items()}
Show solution
def invert(d):
return {v: k for k, v in d.items()}
If two keys share a value, the later one wins โ values must be unique (and hashable) for an inversion to be lossless.
5. Merge score tablesmedium
Write merge(a, b) that combines two dictionaries of scores, adding the values when a name appears in both. Don't modify a or b.
๐ก Copy a with dict(a), then loop over b.items() adding with get.
Show solution
def merge(a, b):
out = dict(a)
for name, score in b.items():
out[name] = out.get(name, 0) + score
return out
The starter's update overwrites Bob's 5 with 2 instead of adding โ and it changes a in place, a classic side-effect bug.
6. Nested datahard
students maps names to a dict with a list of scores. Write top_student(students) that returns the name with the highest average score.
๐ก max(students, key=lambda n: sum(students[n]['scores']) / len(students[n]['scores']))
Show solution
def top_student(students):
def average(name):
scores = students[name]["scores"]
return sum(scores) / len(scores)
return max(students, key=average)
Looping over a dictionary gives its keys, so max(students, key=...) returns a name. A small helper function keeps the key readable.
Python Coding - Learn Python for Android: a real Python 3 interpreter, code editor, 26 example programs and 12 marked exercises.
Frequently asked questions
How do I avoid KeyError in a Python dictionary?
Use d.get(key, default), check with if key in d, or use collections.defaultdict.
Are Python dictionaries ordered?
Yes, since Python 3.7 they keep insertion order. Comparing two dictionaries with == ignores order.
Can a list be a dictionary key?
No โ keys must be hashable (immutable). Use a tuple instead of a list.