Specialized 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: Group records with defaultdict ✓ Passed
Write group_by(records, key) that groups a list of dictionaries by the value of key.
It returns a plain dict (not a defaultdict) mapping each key value to a list of the matching records, in their original order. Records that don't have the key go under None. Use a defaultdict while building the result.
from collections import defaultdict
def group_by(records, key):
groups = defaultdict(list)
# your code here
return groups
people = [
{'name': 'ann', 'city': 'Paris'},
{'name': 'bob', 'city': 'Rome'},
{'name': 'cat'},
{'name': 'dan', 'city': 'Paris'},
]
def test_groups():
"""records are grouped by the key value, in order"""
g = group_by(people, 'city')
assert [p['name'] for p in g.get('Paris', [])] == ['ann', 'dan'], f"Paris group: {g.get('Paris')}"
assert [p['name'] for p in g.get('Rome', [])] == ['bob']
def test_missing_key():
"""records without the key go under None"""
g = group_by(people, 'city')
assert None in g, "no None group"
assert [p['name'] for p in g[None]] == ['cat']
def test_plain_dict():
"""the result is a plain dict, so unknown keys raise KeyError"""
g = group_by(people, 'city')
assert type(g) is dict, f"returned {type(g).__name__}"
try:
g['Berlin']
except KeyError:
pass
else:
raise AssertionError("looking up an unknown group did not raise KeyError")
def test_empty():
"""an empty list gives an empty dict"""
assert group_by([], 'city') == {}
Hints (2)
record.get(key)returnsNonewhen the key is missing, which is exactly the group name you need.- Convert at the end with
dict(groups)so callers get a normal dictionary.
Show a solution
from collections import defaultdict
def group_by(records, key):
groups = defaultdict(list)
for record in records:
groups[record.get(key)].append(record)
return dict(groups)Exercise 2: Can you spell it? ✓ Passed
In a word game you hold some letter tiles. Write two functions using Counter:
- can_spell(word, tiles) returns True if word can be built from the letters in the string tiles (each tile used at most once). - missing_letters(word, tiles) returns a plain dict of the letters you'd still need and how many of each, for example {'p': 1}. It's empty if the word can be spelled.
Treat upper and lower case the same.
from collections import Counter
def can_spell(word, tiles):
return set(word.lower()) <= set(tiles.lower())
def missing_letters(word, tiles):
pass
def test_can_spell_simple():
"""a word using available tiles can be spelled"""
assert can_spell('cab', 'abcd') is True
def test_counts_matter():
"""repeated letters need repeated tiles"""
assert can_spell('apple', 'aple') is False, "'apple' needs two p tiles"
assert can_spell('apple', 'pplae') is True
def test_case_insensitive():
"""case is ignored"""
assert can_spell('Bob', 'obb') is True
def test_missing():
"""missing_letters reports what is lacking"""
assert missing_letters('apple', 'aple') == {'p': 1}
assert missing_letters('banana', 'ban') == {'a': 2, 'n': 1}
def test_missing_none():
"""missing_letters is empty when the word can be spelled"""
result = missing_letters('cab', 'abcd')
assert result == {} and type(result) is dict, f"got {result!r}"
Hints (2)
- Sets lose the counts. Compare two
Counterobjects instead: since Python 3.10,c1 <= c2means every count inc1fits inc2. Counter(word) - Counter(tiles)keeps only the positive differences, which are exactly the missing letters.
Show a solution
from collections import Counter
def can_spell(word, tiles):
return Counter(word.lower()) <= Counter(tiles.lower())
def missing_letters(word, tiles):
return dict(Counter(word.lower()) - Counter(tiles.lower()))Exercise 3: Recently viewed with OrderedDict ✓ Passed
Write a class Recent that tracks the most recently viewed items, keeping at most capacity of them.
- view(item) records that item was viewed. Viewing an item that is already tracked makes it the most recent. When there are more than capacity items, the least recently viewed one is dropped. - items() returns a list of the tracked items, most recent first. - len(recent) gives the number of tracked items.
Use an OrderedDict (the values don't matter, so store None).
from collections import OrderedDict
class Recent:
def __init__(self, capacity):
self.capacity = capacity
self._data = OrderedDict()
def view(self, item):
self._data[item] = None
def items(self):
return list(self._data)
def __len__(self):
return len(self._data)
def test_order():
"""most recent item comes first"""
r = Recent(5)
for x in 'abc':
r.view(x)
assert r.items() == ['c', 'b', 'a'], f"got {r.items()}"
def test_review_moves_to_front():
"""viewing an item again makes it the most recent"""
r = Recent(5)
for x in 'abca':
r.view(x)
assert r.items() == ['a', 'c', 'b'], f"got {r.items()}"
assert len(r) == 3
def test_capacity():
"""the least recently viewed item is dropped"""
r = Recent(2)
for x in 'abac':
r.view(x)
assert r.items() == ['c', 'a'], f"got {r.items()}"
assert len(r) == 2
Hints (2)
- Assigning to an existing key doesn't move it. Call
move_to_end(item)after storing it. - The oldest item is at the front: remove it with
popitem(last=False). For the result,reversed(self._data)walks from newest to oldest.
Show a solution
from collections import OrderedDict
class Recent:
def __init__(self, capacity):
self.capacity = capacity
self._data = OrderedDict()
def view(self, item):
self._data[item] = None
self._data.move_to_end(item)
if len(self._data) > self.capacity:
self._data.popitem(last=False)
def items(self):
return list(reversed(self._data))
def __len__(self):
return len(self._data)Exercise 4: A case-insensitive dictionary ✓ Passed
Write CaseInsensitiveDict, a dictionary whose string keys are case-insensitive: d['Content-Type'], d['content-type'] and d.get('CONTENT-TYPE') all refer to the same entry, and 'CONTENT-TYPE' in d is True.
Store keys lowercased. The behavior must also hold for the constructor, update, get and del. Non-string keys are stored unchanged.
The starter subclasses dict. Switch to UserDict and make it work everywhere.
class CaseInsensitiveDict(dict):
@staticmethod
def _norm(key):
return key.lower() if isinstance(key, str) else key
def __setitem__(self, key, value):
super().__setitem__(self._norm(key), value)
def __getitem__(self, key):
return super().__getitem__(self._norm(key))
def test_get_and_set():
"""[] ignores case"""
d = CaseInsensitiveDict()
d['Content-Type'] = 'text/html'
assert d['content-type'] == 'text/html'
assert d['CONTENT-TYPE'] == 'text/html'
def test_constructor_and_update():
"""keys passed to the constructor or update are lowercased"""
d = CaseInsensitiveDict({'Accept': '*/*'})
d.update({'Host': 'example.com'})
assert sorted(d.keys()) == ['accept', 'host'], f"keys: {list(d.keys())}"
def test_get_and_contains():
"""get() and `in` ignore case"""
d = CaseInsensitiveDict(Accept='*/*')
assert d.get('ACCEPT') == '*/*', f"get returned {d.get('ACCEPT')!r}"
assert 'aCcEpT' in d, "`in` is case-sensitive"
assert d.get('missing', 'n/a') == 'n/a'
def test_delete():
"""del ignores case"""
d = CaseInsensitiveDict(Accept='*/*')
del d['ACCEPT']
assert len(d) == 0
def test_non_string_keys():
"""non-string keys are stored as they are"""
d = CaseInsensitiveDict()
d[1] = 'one'
assert d[1] == 'one' and 1 in d
Hints (2)
- With a
dictsubclass, the constructor,updateandgetskip your overrides. Inherit fromcollections.UserDictinstead. UserDictimplementsinwith its own__contains__(it checksself.datadirectly), andgetrelies onin. Override__contains__and__delitem__too.
Show a solution
from collections import UserDict
class CaseInsensitiveDict(UserDict):
@staticmethod
def _norm(key):
return key.lower() if isinstance(key, str) else key
def __setitem__(self, key, value):
super().__setitem__(self._norm(key), value)
def __getitem__(self, key):
return super().__getitem__(self._norm(key))
def __delitem__(self, key):
super().__delitem__(self._norm(key))
def __contains__(self, key):
return super().__contains__(self._norm(key))