Summary
Write a function that adds a new field to records in a data set (a list of dictionaries), based on existing fields.
Situation
You have a data set (a list of dictionaries) that's missing a field you need, but it can be computed from other fields.
Action
Write a function that will loop through a data set. For each record, it computes a new value based on existing fields, and adds it to the record.
Call it like this:
- compute_change(cleaned_goat_scores)
The function doesn't return a new data set. It modifies the data set passed as a param.
Here's an example:
- def compute_change(goat_scores):
- '''
- Add score differences to the data set.
- The data is changed in-place.
- Parameters
- ----------
- goat_scores : list
- A list of dictionaries with the goats' score.
- '''
- # Loop over list.
- for goat_record in goat_scores:
- # Compute difference.
- change = goat_record['After'] - goat_record['Before']
- # Add difference field to the dictionary.
- goat_record['Difference'] = change
Where referenced