You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python字典映射异常:Grade与Test_Scores关联时缺失第三个元素

Why Your Grade-Score Mapping Is Missing an Entry & How to Fix It

Hey Jenny, let's break down what's going on here and get your test scores mapped correctly.

The Root Problem

Python dictionaries rely on unique keys—you can't have two identical keys in a single dict, because the second occurrence will overwrite the first one. When you run dict(zip(Grades, Test_Scores)), here's what happens:

  1. First, it pairs 'A' with the first test score dict.
  2. Next, it pairs 'B' with the second test score dict.
  3. Finally, it sees another 'B' and replaces the existing 'B' value with the third test score dict.

That's why your output only has two entries—your second test score got overwritten by the third one. Also, note that your "expected output" isn't a valid Python dictionary (it has a standalone dict at the end with no key), so we'll adjust to a structure that's both functional and legal.

Fix 1: Keep All Entries with a List of Tuples

If you just want to preserve every grade-score pair exactly as they're ordered, use a list of tuples instead of a dict. This avoids the key-overwrite issue entirely:

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

# Create a list of (grade, score_dict) tuples
result = list(zip(Grades, Test_Scores))
print(result)

Output:

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

If you want to group all test scores under their corresponding grade (a more logical structure for this data), use collections.defaultdict to collect multiple scores under the same grade key:

from collections import defaultdict

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

# Initialize a dict where each key maps to a list of scores
grade_groups = defaultdict(list)
for grade, score in zip(Grades, Test_Scores):
    grade_groups[grade].append(score)

# Convert to a regular dict if needed
print(dict(grade_groups))

Output:

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

This way, all your test scores are preserved, and the data is organized in a way that's easy to work with (e.g., you can quickly get all 'B' scores by accessing grade_groups['B']).

内容的提问来源于stack exchange,提问作者Jenny_Angels

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:06:40