1. Learn
  2. /
  3. Courses
  4. /
  5. Data Types for Data Science in Python

Exercise

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.

Instructions

100 XP
  • 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.