将字典中的值的平均值存储在单独的字典中-Python

将字典中的值的平均值存储在单独的字典中-Python,python,dictionary,Python,Dictionary,我有一本这样的字典: scores = {'Ben': ['10', '9'], 'Alice': ['10', '10'], 'Tom': ['9', '8']} averages = {'Ben': [9.5], 'Alice': [10], 'Tom': [8.5]} 我已经计算了字典中每个人的平均值,然后我想将平均值存储在单独的字典中。我希望它看起来像这样: scores = {'Ben': ['10', '9'], 'Alice': ['10', '10'], 'Tom': ['9

我有一本这样的字典:

scores = {'Ben': ['10', '9'], 'Alice': ['10', '10'], 'Tom': ['9', '8']}
averages = {'Ben': [9.5], 'Alice': [10], 'Tom': [8.5]}
我已经计算了字典中每个人的平均值,然后我想将平均值存储在单独的字典中。我希望它看起来像这样:

scores = {'Ben': ['10', '9'], 'Alice': ['10', '10'], 'Tom': ['9', '8']}
averages = {'Ben': [9.5], 'Alice': [10], 'Tom': [8.5]}
我使用以下代码计算了平均值:

for key, values in scores.items(): 
  avg = float(sum([int(i) for i in values])) / len(values)
  print(avg)
这将提供以下输出:

9.5
10.0
8.5
如何在单独的字典中输出平均值,如上图所示


提前感谢。

使用听写理解

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.
>>> 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]}

您可以使用字典理解来循环您的项目并计算正确的结果:

>>> 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]}

请注意,您需要将您的值转换为
int
,您可以使用
map
函数
map(int,v)

您可以在一行中使用dict理解来完成此操作:

averages = {k: sum(float(i) for i in v) / len(v) for k, v in scores.items() if v}