简体   繁体   English

更新字典列表值的惯用方法

[英]Idiomatic way of updating the values of list of dictionaries

I have the following two lists:我有以下两个列表:

a = [
    {'name': 'name 1', 'some_value': '123', 'age': None},
    {'name': 'name 2', 'some_value': '345', 'age': None},
    {'name': 'name 3', 'some_value': '678', 'age': None},
]
b = [
    {'name': 'name 2', 'some_value': '345', 'age': 10},
    {'name': 'name 3', 'some_value': '678', 'age': 11},
]

My desired output would be:我想要的 output 将是:

[
    {'name': 'name 1', 'some_value': '123', 'age': None},
    {'name': 'name 2', 'some_value': '345', 'age': 10},
    {'name': 'name 3', 'some_value': '678', 'age': 11},
]

The working solution I have is this:我的工作解决方案是这样的:

for i in b:
    for k, x in enumerate(a):
        if x['name'] == i['name'] and x['some_value'] == i['some_value']:
            a[k]['age'] = i['age']

However I'm looking for a prettier way to achieve this.但是我正在寻找一种更漂亮的方法来实现这一目标。 Any ideas?有任何想法吗?

It would be easier if you modify the structure a bit and make the composite key ( name plus some_value ) the key of a new dictionary, for example:如果您稍微修改结构并使复合键( name加上some_value )成为新字典的键会更容易,例如:

>>> a1 = {(x["name"], x["some_value"]): x["age"] for x in a}
>>> a1.update({(x["name"], x["some_value"]): x["age"] for x in b})
>>> a1
{('name 1', '123'): None, ('name 2', '345'): 10, ('name 3', '678'): 11}

You can use this as it is, or revert it back to the same dict structure:您可以按原样使用它,也可以将其恢复为相同的 dict 结构:

>>> [{"name": key[0], "some_value": key[1], "age": value} for key, value in a1.items()]
[{'name': 'name 1', 'some_value': '123', 'age': None}, 
 {'name': 'name 2', 'some_value': '345', 'age': 10},
 {'name': 'name 3', 'some_value': '678', 'age': 11}]

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

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