姬長信(Redy)

python – 如何合并字典列表


使用以下字典列表:
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'}
]

将它们组合到以下字典列表中的最佳方法是什么:

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
]

或者以不同方式存储数据会更好,例如:

courses = {
    '1456': 'History',
    '316': 'Science',
    '926': 'Geography'
}

谢谢你的帮助.