如何合并词典列表

2024-04-26 00:01:23 发布

您现在位置: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'
}

谢谢你的帮助。


Tags: 方法nameid列表字典informationhistory词典
3条回答

字典基本上是(键,值)对的列表。

对你来说

user_course_score可以只是一个字典(course_id,score),而不是一个字典列表(您只是不必要地使它复杂化了)

类似地,course可以只是(course_id,name)的字典

你最后的建议是正确的:)

Rahul是正确的;字典列表并不是正确的方法。想象一下:字典是数据块之间的映射。最后一个例子courses是存储数据的正确方法;然后可以执行以下操作来存储每个用户的数据:

courses = {
    1456: 'History',
    316: 'Science',
    926: 'Geography'
} # Note the lack of quotes

test_scores = {
    1456: { <user-id>: <score on History test> },
    316: { <user-id>: <score on History test> },
    926: { <user-id>: <score on History test> }
}

下面是一个可能的解决方案:

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

产生:

[{'course_id': 1456, 'name': 'History', 'score': 56},
 {'course_id': 316, 'name': 'Science', 'score': 71},
 {'course_id': 926, 'name': 'Geography'}]

如你所见,我用一本字典(合并)作为中间点。当然,您可以跳过一步,以不同的方式存储数据,但这也取决于您对这些变量的其他用途。

一切顺利。

相关问题 更多 >