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.
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)
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]
Is it because you spelled length wrong the second time so it’s calling it wrong
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.
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)
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]
Is it because you spelled length wrong the second time so it’s calling it wrong