如何合并字典列表

13

使用如下所示的字典列表:

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'
}
谢谢您的帮助。

我接受了Adam的答案,因为它确切地满足了我的要求。其他建议我将数据重构为字典的答案很好,但是对于我的项目,我宁愿不使用ID作为键。 - Chris
4个回答

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')作为中间步骤。当然,如果你以不同的方式存储数据,你可以跳过这一步,但这也取决于你可能对这些变量有什么其他用途。

祝一切顺利。


1
嗨,亚当。我正在使用这种方法来实现同样的功能,但我的字典和列表非常庞大。我想知道你是否知道更快的方法来做到这一点。谢谢。 - Mridang Agarwalla
2
@MridangAgarwalla 你有找到更快的方法吗? - Thameem

3

字典基本上是(key, value)对的列表。

在你的情况下,

user_course_score可以只是(course_id, score)的字典,而不是字典列表(你只是不必要地把它复杂化了)

同样,course可以只是(course_id, name)的字典

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


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

1

你也可以尝试:

[
    course.update(score) for course 
    in courses for score in user_course_score 
    if course['course_id'] == score['course_id']
]

:)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接