Get startedGet started for free

Creating namedtuples for storing data

Often times when working with data, you will use a dictionary just so you can use key names to make reading the code and accessing the data easier to understand. Python has another container called a namedtuple that is a tuple, but has names for each position of the tuple. You create one by passing a name for the tuple type and a list of field names.

For example, Cookie = namedtuple("Cookie", ['name', 'quantity']) will create a container, and you can create new ones of the type using Cookie('chocolate chip', 1) where you can access the name using the name attribute, and then get the quantity using the quantity attribute.

In this exercise, you're going to restructure the penguin weight log data you've been working with into namedtuples for more descriptive code.

This exercise is part of the course

Data Types in Python

View Course

Exercise instructions

  • Import namedtuple from collections.
  • Create a namedtuple called SpeciesDetails with a type name of SpeciesDetails and fields of 'species', 'sex', and 'body_mass'.
  • Create a list called labeled_entries.
  • Iterate over the weight_log list, unpacking it into species, sex, and body_mass, and create a new SpeciesDetails namedtuple instance for each entry and append it to labeled_entries.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Import namedtuple from collections
from collections import ____

# Create the namedtuple: SpeciesDetails
SpeciesDetails = ____(____, ['species', 'sex', 'body_mass'])

# Create the empty list: labeled_entries
labeled_entries = []

# Iterate over the weight_log entries
for ____, ____, ____ in ____:
    # Append a new SpeciesDetails namedtuple instance for each entry to labeled_entries
    ____
    
print(labeled_entries[:5])
Edit and Run Code