Reputation: 161
dict = {a:[2,4,5],b:[4,6,7],c:[3,1,1]}
Above is an example of a dictionary I have. The length of the nested lists will always be 3 (due to other blocks of code). I have figured out how to sort alphabetically and by highest value of the list inside the dictionary. I am struggling to find a way to calculate the highest AVERAGE score. Below is the desired output:
>>> get_average(dict)
>>> b : 5.66
>>> a : 3.66
>>> c : 1.66
Any tips or even a solution? I'm pretty sure the most efficient way is to use lambda. Can I modify this code to get the average:
sorted(dict.items(), key=operator.itemgetter(1))
Upvotes: 0
Views: 378
Reputation: 4078
try this:
d = {'a':[2,4,5], 'b':[4,6,7], 'c':[3,1,1]}
sort = sorted(d, key=lambda k: sum(d[k]) / 3, reverse=True)
for i in sort:
print(i, ":", sum(d[i]) / 3)
Upvotes: 2
Reputation: 362847
First, build a map of the averages using a dict comprehension:
>>> d = {'a':[2,4,5], 'b':[4,6,7], 'c':[3,1,1]}
>>> def mean(L):
return float(sum(L))/len(L)
...
>>> d_avg = {k: mean(v) for k, v in d.items()}
>>> d_avg
{'a': 3.6666666666666665, 'b': 5.666666666666667, 'c': 1.6666666666666667}
Then you can sort that by value:
>>> sorted(d_avg, key=d_avg.get, reverse=True)
['b', 'a', 'c']
Upvotes: 2