JTiger
JTiger

Reputation: 31

Get averages of lists in a dictionary

I have a dictionary that has lists inside it eg:

dict = {'Monday,': [10, 20], 'Tuesday,': [20, 20], 'Wednesday,': [30, 40], 'Thursday,': [5, 25], 'Friday,': [100, 20], 'Saturday,': [40, 10], 'Sunday,': [35, 25]}

And I need to get an average of each day eg:

{'Monday,': [15.00], 'Tuesday,': [20.00], 'Wednesday,': [35.00], 'Thursday,': [15.00], 'Friday,': [60.00], 'Saturday,': [25.00], 'Sunday,': [30.00]}

I have this at the moment but it is not working

average = sum(dict) / len(dict)

Upvotes: 1

Views: 58

Answers (1)

adrtam
adrtam

Reputation: 7211

first, please don't name your dict as dict because that's a name of a python built-in

This will work for you:

average = {key: sum(val)/len(val) for key, val in dict.items()}

but beware that you assumed all lists are of numbers and no list is empty.

Upvotes: 4

Related Questions