Python字典映射异常:Grade与Test_Scores关联时缺失第三个元素
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:
- First, it pairs
'A'with the first test score dict. - Next, it pairs
'B'with the second test score dict. - 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})]
Fix 2: Group Scores by Grade (Recommended)
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

