Dictionaries · Practice
Quiz & exercises
Answer each question to see the explanation. Your best score is saved in this browser.
Quiz
Coding exercises
Write your code, then press Check (or Shift+Enter) to run the tests. Drafts are saved as you type.
Exercise 1: Word frequencies ✓ Passed
Write word_counts(text) that returns a dict mapping each word in text to the number of times it appears.
- Words are separated by whitespace (use text.split()). - Ignore case: 'The' and 'the' are the same word (store it lowercase). - Strip the punctuation characters .,;:!? from both ends of each word, and skip anything that becomes empty. - Keys must appear in the order each word is first seen.
Use a plain dict (no collections).
def word_counts(text):
counts = {}
# your code here
return counts
def test_simple():
"""counts repeated words"""
assert word_counts('a b a') == {'a': 2, 'b': 1}, word_counts('a b a')
def test_case_and_punctuation():
"""ignores case and strips punctuation"""
result = word_counts('The cat. the CAT, the hat!')
assert result == {'the': 3, 'cat': 2, 'hat': 1}, result
def test_order():
"""keys are in first-seen order"""
result = word_counts('zebra apple zebra mango apple')
assert list(result) == ['zebra', 'apple', 'mango'], list(result)
def test_skip_empty():
"""punctuation-only tokens are skipped"""
result = word_counts('hi , there ... hi !')
assert result == {'hi': 2, 'there': 1}, result
def test_empty_text():
"""empty text gives an empty dict"""
assert word_counts('') == {}
Hints (2)
word.strip('.,;:!?')removes those characters from both ends.counts.get(word, 0) + 1gives the new count whether or not the word was seen before.
Show a solution
def word_counts(text):
counts = {}
for word in text.split():
word = word.strip('.,;:!?').lower()
if word:
counts[word] = counts.get(word, 0) + 1
return countsExercise 2: Invert a dictionary ✓ Passed
Write invert(d) that returns a new dict mapping each value of d to a list of the keys that had that value.
- The keys in each list appear in the same order as in d. - The result's keys appear in the order each value is first seen. - Don't modify d.
Example: invert({'a': 1, 'b': 2, 'c': 1}) returns {1: ['a', 'c'], 2: ['b']}.
def invert(d):
# your code here
pass
def test_example():
"""groups keys by value"""
result = invert({'a': 1, 'b': 2, 'c': 1})
assert result == {1: ['a', 'c'], 2: ['b']}, result
def test_orders():
"""value order and key order follow the input"""
result = invert({'x': 'b', 'y': 'a', 'z': 'b', 'w': 'a'})
assert list(result.items()) == [('b', ['x', 'z']), ('a', ['y', 'w'])], result
def test_separate_lists():
"""each value gets its own list"""
result = invert({'a': 1, 'b': 2})
result[1].append('extra')
assert result[2] == ['b'], "lists are shared between values"
def test_not_mutated():
"""the input dict is unchanged"""
d = {'a': 1, 'b': 1}
invert(d)
assert d == {'a': 1, 'b': 1}, d
def test_empty():
"""empty dict"""
assert invert({}) == {}
Hints (3)
- Loop over
d.items()to get each key with its value. result.setdefault(value, [])returns the list forvalue, creating it the first time. Append the key to it.dict.fromkeys(values, [])would share one list between all values, so avoid it.
Show a solution
def invert(d):
result = {}
for key, value in d.items():
result.setdefault(value, []).append(key)
return resultExercise 3: Merge nested configuration ✓ Passed
Write deep_merge(base, override) that returns a new dict combining two nested configuration dicts:
- Keys from both dicts appear in the result, base's keys first (in their order), then new keys from override. - If a key is in both and both values are dicts, merge them recursively the same way. - Otherwise the value from override wins. - Neither input may be modified, and changing the result (even its nested dicts) must not change the inputs.
def deep_merge(base, override):
# a shallow merge is not enough!
return base | override
def test_flat():
"""flat dicts: override wins, order kept"""
result = deep_merge({'a': 1, 'b': 2}, {'b': 20, 'c': 3})
assert list(result.items()) == [('a', 1), ('b', 20), ('c', 3)], result
def test_nested():
"""nested dicts are merged recursively"""
base = {'db': {'host': 'localhost', 'port': 5432}, 'debug': False}
override = {'db': {'host': 'prod.example.com'}, 'debug': True}
result = deep_merge(base, override)
assert result == {'db': {'host': 'prod.example.com', 'port': 5432}, 'debug': True}, result
def test_deeper():
"""three levels deep"""
result = deep_merge({'a': {'b': {'c': 1, 'd': 2}}}, {'a': {'b': {'d': 3}}})
assert result == {'a': {'b': {'c': 1, 'd': 3}}}, result
def test_non_dict_replaces():
"""a non-dict value replaces a dict (and vice versa)"""
assert deep_merge({'a': {'x': 1}}, {'a': 5}) == {'a': 5}
assert deep_merge({'a': 5}, {'a': {'x': 1}}) == {'a': {'x': 1}}
def test_inputs_unchanged():
"""inputs are not mutated"""
base = {'db': {'host': 'localhost', 'port': 5432}}
override = {'db': {'host': 'prod'}}
deep_merge(base, override)
assert base == {'db': {'host': 'localhost', 'port': 5432}}, base
assert override == {'db': {'host': 'prod'}}, override
def test_result_independent():
"""mutating the result's nested dicts leaves the inputs alone"""
base = {'db': {'host': 'localhost'}, 'only_base': {'k': 1}}
override = {'only_override': {'k': 2}}
result = deep_merge(base, override)
result['db']['host'] = 'changed'
result['only_base']['k'] = 99
result['only_override']['k'] = 99
assert base == {'db': {'host': 'localhost'}, 'only_base': {'k': 1}}, base
assert override == {'only_override': {'k': 2}}, override
Hints (3)
- Start from a deep copy of
base, so nothing in the result is shared with it. - Loop over
override.items(). When both sides hold a dict, calldeep_mergerecursively on them; otherwise store (a deep copy of) the override value. - Assigning to an existing key keeps its position, so
base's key order is preserved automatically.
Show a solution
from copy import deepcopy
def deep_merge(base, override):
result = deepcopy(base)
for key, value in override.items():
if isinstance(result.get(key), dict) and isinstance(value, dict):
result[key] = deep_merge(result[key], value)
else:
result[key] = deepcopy(value)
return resultExercise 4: A hashable playing card ✓ Passed
Write a class Card(rank, suit) that can be used as a dictionary key and in sets:
- Two cards are equal when their rank and suit are equal. Comparing a Card with a non-Card gives False (return NotImplemented from __eq__ for other types). - Equal cards must have equal hashes. - rank and suit are read-only properties: assigning to them raises AttributeError. - repr(Card('A', 'spades')) is "Card('A', 'spades')".
class Card:
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
def __eq__(self, other):
if isinstance(other, Card):
return (self.rank, self.suit) == (other.rank, other.suit)
return NotImplemented
def test_equality():
"""cards compare by value"""
assert Card('A', 'spades') == Card('A', 'spades')
assert Card('A', 'spades') != Card('K', 'spades')
assert Card('A', 'spades') != ('A', 'spades')
def test_hash():
"""equal cards have equal hashes"""
assert hash(Card('Q', 'hearts')) == hash(Card('Q', 'hearts'))
def test_dict_key():
"""an equal card finds the dict entry"""
scores = {Card('A', 'spades'): 11}
assert scores[Card('A', 'spades')] == 11
def test_set_dedupes():
"""a set keeps one copy of equal cards"""
cards = {Card('2', 'clubs'), Card('2', 'clubs'), Card('3', 'clubs')}
assert len(cards) == 2, len(cards)
def test_read_only():
"""rank and suit can't be reassigned"""
c = Card('J', 'diamonds')
for attr in ('rank', 'suit'):
try:
setattr(c, attr, 'x')
except AttributeError:
continue
raise AssertionError(f'{attr} could be reassigned')
def test_repr():
"""repr shows the constructor call"""
assert repr(Card('A', 'spades')) == "Card('A', 'spades')", repr(Card('A', 'spades'))
Hints (4)
- The starter defines
__eq__, so Python has set__hash__toNone. Define__hash__yourself. - Hash the same fields
__eq__compares:hash((self.rank, self.suit)). - Store the data as
_rankand_suit, and exposerankandsuitwith@property(no setter). - Use
!rin the f-string so the strings get their quotes in the repr.
Show a solution
class Card:
def __init__(self, rank, suit):
self._rank = rank
self._suit = suit
@property
def rank(self):
return self._rank
@property
def suit(self):
return self._suit
def __repr__(self):
return f'Card({self.rank!r}, {self.suit!r})'
def __eq__(self, other):
if isinstance(other, Card):
return (self.rank, self.suit) == (other.rank, other.suit)
return NotImplemented
def __hash__(self):
return hash((self.rank, self.suit))