biscuit
biscuit

Reputation: 1

How to create statistical calculation from a new calculation made from values in dictionaries within a list, python 3

I have a list of dictionaries, for which I have extracted two values from each dictionary, and divided by each other to create a new item. I would like to find the mode and median of these new items. There are quite a few of them, so I don't want to type each new item in to form the list.

from statistics import median
from statistics import mean
for stats in body_stats:
    size = [stats['weight']/stats['height']]
median_size = median(size) 
mode_size = mode(size)
print(mode_size, median_size)

This code appears to print the last calculation made, rather than working out what the mode/median are. I'm assuming this result is due to the new calculations not being part of one whole list. They are printed as a series of lists for each value.

How would I get them to form a list without typing each calculation individually?

Is there another way to find out the statistical calculations from the calculations I created?

Thank you for your help!

Upvotes: 0

Views: 84

Answers (2)

Nick Vitha
Nick Vitha

Reputation: 476

You need to append each item to the list. What you're doing currently with this line:

size = [stats['weight']/stats['height']]

Is creating a new list with a single element each time. Each time the loop runs, it will overwrite the size variable with a single-element list

What you need to do instead is

from statistics import median
from statistics import mean

size = [] # create a "size" variable that is the list type
for stats in body_stats:
    size.append(stats['weight']/stats['height']) # append the calculation 
median_size = median(size) 
mode_size = mode(size)
print(mode_size, median_size)

Upvotes: 1

josemz
josemz

Reputation: 1312

The problem is you are saving a list of one item in each iteration. Instead, you can use a generator and feed it to median and mode like this.

median_size = median(stats['weight']/stats['height'] for stats in body_stats)
mode_size = mode(stats['weight']/stats['height'] for stats in body_stats)

Upvotes: 2

Related Questions