Specialized Dictionaries · Practice

Quiz & exercises

Answer each question to see the explanation. Your best score is saved in this browser.

Quiz

1. What does this print?
from collections import defaultdict
d = defaultdict(list)
print(d.get('a'), 'a' in d)
d['b']
print(dict(d))
2. Which of these is a correct way to create a defaultdict whose missing keys start as empty lists?
3. What does this print?
from collections import Counter
c = Counter('banana')
print(c['z'], 'z' in c, len(c))
4. What does this print?
from collections import Counter
c1 = Counter(a=3, b=1)
c2 = Counter(a=1, b=2)
print(c1 - c2)
c1.subtract(c2)
print(c1)
5. What does this print? (Python 3.10+)
from collections import Counter
stock = Counter(eggs=6, milk=1, flour=2)
recipe = Counter(eggs=2, flour=2)
print(recipe <= stock, stock.total())
6. What does this print?
from collections import Counter
print(Counter(a=2, b=0) == Counter(a=2))
print(list(Counter(a=2, b=0).elements()))
7. What does this print?
from collections import OrderedDict
a = OrderedDict(x=1, y=2)
b = OrderedDict(y=2, x=1)
c = {'y': 2, 'x': 1}
print(a == b, a == c, b == c)
8. What does this print?
from collections import OrderedDict
d = OrderedDict.fromkeys('abcd')
d.move_to_end('b')
d.move_to_end('d', last=False)
d.popitem(last=False)
print(''.join(d))
9. Since Python 3.7, which of these does a plain dict not offer directly?
10. What does this print?
from collections import ChainMap
d1 = {'a': 1}
d2 = {'a': 10, 'b': 20}
cm = ChainMap(d1, d2)
cm['b'] = 99
del cm['a']
print(cm['a'], cm['b'], d2)
11. How does a ChainMap lookup differ from {**d1, **d2}?
12. class D(dict) overrides __setitem__ to reject negative values. Which statement still stores -1 without any error?

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

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.

Hints (2)
  1. record.get(key) returns None when the key is missing, which is exactly the group name you need.
  2. 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?

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.

Hints (2)
  1. Sets lose the counts. Compare two Counter objects instead: since Python 3.10, c1 <= c2 means every count in c1 fits in c2.
  2. 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

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).

Hints (2)
  1. Assigning to an existing key doesn't move it. Call move_to_end(item) after storing it.
  2. 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

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.

Hints (2)
  1. With a dict subclass, the constructor, update and get skip your overrides. Inherit from collections.UserDict instead.
  2. UserDict implements in with its own __contains__ (it checks self.data directly), and get relies on in. 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))