Search code examples
pythonlistdictionarymean

mean median and mode dictionary list python 3


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.


Solution

  • 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)