字典的键值数量未正确输出

问题描述 投票:0回答:1

[尝试为Test_Scores分配成绩时(计算平均值时,仅返回两个分配的字典。由于某种原因,最后一个不会显示。我将如何显示第三本词典?

Test_Scores = [{'test_1': 90, 'test_2': 80, 'test_3': 95},
 {'test_1': 92, 'test_2': 75, 'test_3': 80},
 {'test_1': 80, 'feature_2': 81, 'test_3': 82}]

Grades = ['A', 'B', 'B']

Empty_dict = {}
Empty_dict = dict(zip(Grades, Test_Scores))
print(Empty_dict)

我期望类似:

{'A': {'test_1': 90, 'test_2': 80, 'test_3': 95}, 'B': {'test_1': 92, 
'test_2': 75, 'test_3': 80}, {'test_1': 80, 'feature_2': 81, 'test_3': 
82}})

以证明三个测试的平均值是所分配的键。

但是,我得到:

{'A': {'test_1': 90, 'test_2': 80, 'test_3': 95}, 'B': {'test_1': 80, 
'feature_2': 81, 'test_3': 82}}
python dictionary nested
1个回答
2
投票

通过执行dict(zip(Grades, Test_Scores)),用最后一次出现覆盖B的值,相反,您可以这样做:

Empty_dict = {}
for score, grade in zip(Test_Scores, Grades):
    Empty_dict.setdefault(grade, []).append(score)

print(Empty_dict)

输出

{'A': [{'test_1': 90, 'test_2': 80, 'test_3': 95}], 'B': [{'test_1': 92, 'test_2': 75, 'test_3': 80}, {'test_1': 80, 'feature_2': 81, 'test_3': 82}]}
© www.soinside.com 2019 - 2024. All rights reserved.