Reputation: 49
I have a dictionary that looks like this:
scores = {'Ben': ['10', '9'], 'Alice': ['10', '10'], 'Tom': ['9', '8']}
I have calculated the average of the values for each person in the dictionary and I want to then store the averages in a separate dictionary. I would like it to look like this:
averages = {'Ben': [9.5], 'Alice': [10], 'Tom': [8.5]}
I have calculated the averages using this code:
for key, values in scores.items():
avg = float(sum([int(i) for i in values])) / len(values)
print(avg)
This gives the following output:
9.5
10.0
8.5
How can I output the averages in a separate dictionary as shown above?
Thanks in advance.
Upvotes: 1
Views: 216
Reputation: 9946
you can do this with a dict comprehension in one line:
averages = {k: sum(float(i) for i in v) / len(v) for k, v in scores.items() if v}
Upvotes: 0
Reputation: 107297
You can use a dictionary comprehension to loop over your items and calculate the proper result:
>>> from __future__ import division
>>> scores = {'Ben': ['10', '9'], 'Alice': ['10', '10'], 'Tom': ['9', '8']}
>>> scores = {k:[sum(map(int,v))/len(v)] for k,v in scores.items()}
>>> scores
{'Ben': [9.5], 'Alice': [10.0], 'Tom': [8.5]}
Note that you need to convert your values to int
that you can do it with map
function map(int,v)
.
Upvotes: 0
Reputation: 174706
Use dict_comprehension.
>>> scores = {'Ben': ['10', '9'], 'Alice': ['10', '10'], 'Tom': ['9', '8']}
>>> {i:[float(sum(int(x) for x in scores[i]))/len(scores[i])] for i in scores}
{'Ben': [9.5], 'Alice': [10.0], 'Tom': [8.5]}
Upvotes: 0
Reputation: 14098
averages = {} # Create a new empty dictionary to hold the averages
for key, values in scores.items():
averages[key] = float(sum([int(i) for i in values])) / len(values)
# Rather than store the averages in a local variable, store them in under the appropriate key in your new dictionary.
Upvotes: 1