Get startedGet started for free

Using dataclasses

Let's put our WeightEntry dataclass we created in the prior exercise to use. We'll create an instance of the WeightEntry for each entry in the weight_log and then use the mass_to_flipper_length_ratio property we added to perform the calculation. Here is a reminder of our WeightEntry dataclass.

@dataclass
class WeightEntry:
    # Define the fields on the class
    species: str
    flipper_length: int
    body_mass: int
    sex: str

    @property
    def mass_to_flipper_length_ratio(self):
        return self.body_mass / self.flipper_length

This exercise is part of the course

Data Types in Python

View Course

Exercise instructions

  • Create an empty list called labeled_entries.
  • Iterate over the weight_log entries using tuple expansion to break out species, flipper_length, body_mass, sex.
    • Append a new WeightEntry dataclass instance for each entry to labeled_entries.
  • Print a list of the first 5 mass_to_flipper_length_ratio values using a list comprehension.

Hands-on interactive exercise

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

# Create the empty list: labeled_entries
labeled_entries = []

# Iterate over the weight_log entries
for species, flipper_length, body_mass, ____ in weight_log:
    # Append a new WeightEntry instance to labeled_entries
    ____.____(____(species, flipper_length, body_mass, ____))
    
# Print a list of the first 5 mass_to_flipper_length_ratio values
print([____.____ for entry in labeled_entries[____]])
Edit and Run Code