使用以下字典列表:
user_course_score = [
{'course_id': 1456, 'score': 56},
{'course_id': 316, 'score': 71}
]
courses = [
{'course_id': 1456, 'name': 'History'},
{'course_id': 316, 'name': 'Science'},
{'course_id': 926, 'name': 'Geography'}
]
Run Code Online (Sandbox Code Playgroud)
将它们组合到以下字典列表中的最佳方法是什么:
user_course_information = [
{'course_id': 1456, 'score': 56, 'name': 'History'},
{'course_id': 316, 'score': 71, 'name': 'Science'},
{'course_id': 926, 'name': 'Geography'} # Note: the student did not take this test
]
Run Code Online (Sandbox Code Playgroud)
或者以不同方式存储数据会更好,例如:
courses = {
'1456': 'History',
'316': 'Science',
'926': 'Geography'
}
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助.
Ada*_*dam 23
这是一个可能的解决方案:
def merge_lists(l1, l2, key):
merged = {}
for item in l1+l2:
if item[key] in merged:
merged[item[key]].update(item)
else:
merged[item[key]] = item
return merged.values()
courses = merge_lists(user_course_score, courses, 'course_id')
Run Code Online (Sandbox Code Playgroud)
生产:
[{'course_id': 1456, 'name': 'History', 'score': 56},
{'course_id': 316, 'name': 'Science', 'score': 71},
{'course_id': 926, 'name': 'Geography'}]
Run Code Online (Sandbox Code Playgroud)
如您所见,我使用字典('合并')作为中途点.当然,您可以通过不同方式存储数据来跳过步骤,但这也取决于您对这些变量的其他用途.
祝一切顺利.
| 归档时间: |
|
| 查看次数: |
6616 次 |
| 最近记录: |