Dictionaries · Practice

Quiz & exercises

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

Quiz

1. Which of these can be used as a dictionary key?
2. What does this print?
d = {1: 'a', 1.0: 'b', True: 'c'}
print(d)
3. Why must two objects that compare equal (a == b) have the same hash?
4. What does this print?
groups = dict.fromkeys(['x', 'y'], [])
groups['x'].append(1)
print(groups)
5. What does this print?
d = {'a': 1, 'b': 2, 'c': 3}
d['a'] = 10
d['d'] = 4
print(d.popitem(), list(d))
6. What does this print?
d = {'a': 1}
print(d.setdefault('a', 100), d.setdefault('b', 2), d)
7. What does this print?
d = {'a': 1, 'b': 2}
keys = d.keys()
d['c'] = 3
print(len(keys))
8. Which expression raises a TypeError?
d1 = {'a': 1, 'b': [2]}
d2 = {'b': [2], 'c': 3}
9. What does this print?
d1 = {'a': 1, 'b': 2}
d2 = {'b': 20, 'c': 30}
print(d1 | d2, d2 | d1)
10. What does this print?
d = {'cfg': {'debug': False}, 'tags': ['a']}
c = d.copy()
c['cfg']['debug'] = True
c['tags'] = ['b']
print(d)
11. What does this print?
class P:
    def __init__(self, x):
        self.x = x
    def __eq__(self, other):
        return isinstance(other, P) and self.x == other.x

try:
    print(len({P(1), P(1)}))
except TypeError as ex:
    print('TypeError')
12. A Point used as a dict key has its x attribute changed after insertion, which changes its hash. What usually happens when you then look it up with the same object?

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

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

Hints (2)
  1. word.strip('.,;:!?') removes those characters from both ends.
  2. counts.get(word, 0) + 1 gives 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 counts

Exercise 2: Invert a dictionary

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']}.

Hints (3)
  1. Loop over d.items() to get each key with its value.
  2. result.setdefault(value, []) returns the list for value, creating it the first time. Append the key to it.
  3. 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 result

Exercise 3: Merge nested configuration

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.

Hints (3)
  1. Start from a deep copy of base, so nothing in the result is shared with it.
  2. Loop over override.items(). When both sides hold a dict, call deep_merge recursively on them; otherwise store (a deep copy of) the override value.
  3. 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 result

Exercise 4: A hashable playing card

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

Hints (4)
  1. The starter defines __eq__, so Python has set __hash__ to None. Define __hash__ yourself.
  2. Hash the same fields __eq__ compares: hash((self.rank, self.suit)).
  3. Store the data as _rank and _suit, and expose rank and suit with @property (no setter).
  4. Use !r in 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))