简体   繁体   中英

Get the average of a list for each key in a dict

I have a defaultdict that maps names to a list of scores. I need to work out the average scores of students.

scores = {"Aaron" : ["1" , "3" , "4"] , "Joe" : ["3" , "7" , "2"] , "Bob" : ["7" , "4" , "8"]}

How can I get the averages in a new dict?

averages = {"Aaron" : 2.7 , "Joe" : 4 , "Bob" : 13.7}

Convert each value from a string to a float, take the average, and build a new dict.

scores = {"Aaron" : ["1" , "3" , "4"] , "Joe" : ["3" , "7" , "2"] , "Bob" : ["7" , "4" , "8"]}
averages = {key: sum(float(i) for i in value) / len(value) for key, value in scores.items()}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM