简体   繁体   English

如何使用另一个词典列表更新词典列表?

[英]How to update list of dictionaries using another list of dictionaries?

I have two lists as shown below. 我有两个列表,如下所示。 I want to update the new list using the old list. 我想使用旧列表更新新列表。 The criteria to update the new list are matching values for name in old list. 更新新列表的条件是旧列表中name匹配值。 What is the best way to do it? 最好的方法是什么?

Input 输入

old_list = [{'age': 35, 'name': 'james'}, {'age': 42, 'name': 'bob'}]

new_list = [{'name': 'peter'}, {'name': 'james'}, {'age': 50, 'name': 'bob'}]

Expected Output 预期产出

[{'name': 'peter'}, {'age': 35, 'name': 'james'}, {'age': 42, 'name': 'bob'}]

Edit: Adding my solution 编辑:添加我的解决方案

One solution that I know to solve this using multiple loops and if conditions. 我知道使用多个循环和条件来解决这个问题的一个解决方案。 It is not the compete solution as I need to handle multiple scenarios like where key is not present etc. 它不是竞争解决方案,因为我需要处理多个场景,例如键不存在等。

for x in new_col_list:
    for y in old_col_list:
        if x['name'] == y['name']:
            x['age'] = y['age']
            continue

print new_col_list

You need a structure that will allow you to do the lookup of items in one list from the other. 您需要一种结构,允许您从一个列表中查找另一个列表中的项目。 A dictionary provides such a structure: 字典提供了这样的结构:

lookup = {x['name']: x for x in new_list}
lookup.update({x['name']: x for x in old_list})

You can then convert back to a list if you really want to: 如果您真的想要,您可以转换回列表:

result = list(lookup.values())

In Python 3.6+, the order of the values will be all the elements of the new list, followed by all the missing elements added from the old list in the order they were in the old list. 在Python 3.6+中,值的顺序将是新列表的所有元素,后面是旧列表中按旧列表中的顺序添加的所有缺少的元素。 For older versions of Python, the same can be achieved by collections.OrderedDict : 对于旧版本的Python,可以通过collections.OrderedDict实现相同的功能:

lookup = OrderedDict((x['name'], x) for x in new_list)
lookup.update((x['name'], x) for x in old_list)

Without the ordering, the result of dict.values() will be in arbitrary order, and may change between runs of the interpreter. 如果没有排序, dict.values()的结果将是任意顺序,并且可能在解释器的运行之间发生变化。

Appendix 附录

Any time you see a dictionary comprehension, it is functionally equivalent to a for loop. 每当你看到字典理解时,它在功能上等同于for循环。 Here is the "expanded" version of the first suggested code: 这是第一个建议代码的“扩展”版本:

lookup = {}
for d in new_list:
    lookup[d['name']] = d
for d in old_list:
    lookup[d['name']] = d

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM