Tuples as Data Records · Practice

Quiz & exercises

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

Quiz

1. What is printed?
a = (5)
b = 5,
print(type(a).__name__, type(b).__name__)
2. What does this print?
record = 'DJIA', 2018, 1, 19, 25_987, 26_072
symbol, *middle, close = record
print(middle)
3. What does collections.namedtuple('Point2D', 'x y') return?
4. What is printed?
from collections import namedtuple
Pt = namedtuple('Point', 'x y')
print(Pt(1, 2))
5. What is printed?
from collections import namedtuple
P = namedtuple('P', 'x y')
p = P(1, 2)
q = p._replace(x=10)
print(p, q, p is q)
6. What is printed?
from collections import namedtuple
V = namedtuple('V', 'a b c', defaults=(1, 2))
print(V(0))
7. What is printed?
from collections import namedtuple
Data = namedtuple('Data', 'a b')
d = dict(b=2, a=1)
print(Data(*d.values()), Data(**d))
8. Which call raises a ValueError?
9. What is printed?
from collections import namedtuple
Point2D = namedtuple('Point2D', 'x y')
Vector2D = namedtuple('Vector2D', 'dx dy')
print(Point2D(1, 2) == (1, 2), Point2D(1, 2) == Vector2D(1, 2))
10. What is printed?
from collections import namedtuple
P = namedtuple('P', 'x y')
p = P(3, 4)
field = 'y'
print(getattr(p, field), getattr(p, 'z', 0))
11. Which of these does not produce instances that are tuples?

Coding exercises

Write your code, then press Check (or Shift+Enter) to run the tests. Drafts are saved as you type.

Exercise 1: Dictionaries to named tuples

Write tuplify_dicts(dicts) that takes a list of dictionaries with string keys and returns a list of named tuples, one per dictionary, all instances of one named tuple class called 'Struct'.

- The fields are all keys used in any of the dictionaries, in alphabetical order. - A key missing from a dictionary becomes None in its record. - Values must end up in the right fields regardless of each dictionary's key order.

Hints (3)
  1. Collect every key with a set comprehension: {key for d in dicts for key in d}, then sorted(...) it.
  2. defaults=(None,) * len(keys) gives every field a default of None.
  3. Create each record with Struct(**d) so values are matched to fields by name.
Show a solution
from collections import namedtuple

def tuplify_dicts(dicts):
    keys = sorted({key for d in dicts for key in d})
    Struct = namedtuple('Struct', keys, defaults=(None,) * len(keys))
    return [Struct(**d) for d in dicts]

Exercise 2: Extend a record type

Write extend(cls, name, *new_fields) that takes an existing named tuple class and returns a new named tuple class called name with all of cls's fields followed by new_fields.

The new fields must default to None, so that an old record can be upgraded with New(*old). The original fields stay required.

Example: StockExt = extend(Stock, 'StockExt', 'previous_close').

Hints (2)
  1. cls._fields is a tuple of strings, and new_fields (from *new_fields) is a tuple too, so + joins them.
  2. Defaults apply to the rightmost fields, so len(new_fields) defaults cover exactly the new ones.
Show a solution
from collections import namedtuple

def extend(cls, name, *new_fields):
    return namedtuple(name, cls._fields + new_fields,
                      defaults=(None,) * len(new_fields))

Exercise 3: Return a named result

min_max_mean(values) currently returns a plain tuple. Change it to return a named tuple of class Summary with fields minimum, maximum and mean (in that order), so callers can write result.mean while existing code such as lo, hi, avg = min_max_mean(data) keeps working.

For an empty list, return a Summary whose three fields are all None.

Hints (3)
  1. Define Summary = namedtuple('Summary', 'minimum maximum mean') once, outside the function.
  2. A named tuple is still a tuple, so unpacking works unchanged.
  3. Handle the empty case first: if not values: ...
Show a solution
from collections import namedtuple

Summary = namedtuple('Summary', 'minimum maximum mean')

def min_max_mean(values):
    if not values:
        return Summary(None, None, None)
    return Summary(min(values), max(values), sum(values) / len(values))