mean median and mode dictionary list python 3

Question:

I need to calculate the mean, median and mode of the name of a London Borough. I have created a dictionary list and tried importing the statistics functions to work it out.

n = [
{'name': 'Barking and Dagenham', 'length': 19.0},
{'name': 'Barnet', 'length': 6.0},
{'name': 'Bexley', 'length': 6.0},
]

I tried this:

mean_l = mean(n['lenght'])
print('The mean length of the name of a London Borough is', mean_l)

however it keeps on giving me the following error:

TypeError: list indices must be integers or slices, not str

Any help is appreciated.

Asked By: Annie

||

Answers:

Something like this should work. Create a list containing all lengths, then apply the appropriate statistical function to that list.

import numpy as np
import statistics

lengths = [x['length'] for x in n]

mean_length = np.mean(lengths)
median_length = np.median(lengths)
mode_length = statistics.mode(lengths)
Answered By: sjw

You are not handling your list n the way you expect it. When you write

n[x]

then python will try to look at position x in the list. If you now do

n['length']

then python doesn’t know what to do, because there is no position 'length' in your list. You can do

n[0]['length']

because the elements in your list (indexed with integers) are dictionaries. I think you can solve this by creating a list that only consists of the values for the length field like so:

length_list = [d['length'] for d in n]
Answered By: FlyingTeller

Is it because you spelled length wrong the second time so it’s calling it wrong

Answered By: Thunder061005
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.