如何合并字典列表

13 投票
4 回答
8733 浏览
提问于 2025-04-16 02:24

假设你有一些字典的列表,比如下面这样的:

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

谢谢你的帮助。

4 个回答

2

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> }
}
3

字典其实就是一组(键,值)对的列表。

在你的例子中,

user_course_score 可以直接用一个字典来表示(课程ID,分数),而不是用一个字典的列表(这样做会让事情变得复杂,不必要)。

同样,course 也可以用一个字典来表示(课程ID,课程名称)。

你最后提到的做法是正确的哦 :)

24

这里有一个可能的解决方案:

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

你可以看到,我用了一个字典(叫做'merged')作为中间步骤。当然,你也可以通过不同的方式来存储数据,从而省略这一步,但这也取决于你对这些变量的其他用途。

祝一切顺利。

撰写回答