【问题标题】:How to merge lists of dictionaries如何合并字典列表
【发布时间】:2016-07-05 16:39:25
【问题描述】:

带有如下字典列表:

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

感谢您的帮助。

【问题讨论】:

  • 我接受了亚当的回答,因为它完全符合我的要求。其他答案 - 建议我将数据重组为字典 - 工作正常,但对于我的项目,我宁愿不使用 id 作为键。

标签: python


【解决方案1】:

这是一个可能的解决方案:

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

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

一切顺利。

【讨论】:

  • 嘿亚当。我正在使用这种方法来完成相同的操作,但我的字典和列表非常庞大。我想知道你是否知道更快的方法来做到这一点。谢谢。
  • @MridangAgarwalla 你找到更快的方法了吗??
【解决方案2】:

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

在你的情况下,

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

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

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

【讨论】:

    【解决方案3】:

    拉胡尔是正确的;字典列表不是这样做的正确方法。可以这样想:字典是数据片段之间的映射。您的最后一个示例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> }
    }
    

    【讨论】:

      【解决方案4】:

      你也可以试试:

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

      :)

      【讨论】:

        猜你喜欢
        • 2020-08-11
        • 2021-07-29
        • 2020-08-06
        • 2016-01-02
        • 1970-01-01
        • 1970-01-01
        • 2019-03-12
        • 1970-01-01
        相关资源
        最近更新 更多