简体   繁体   中英

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:

[
    {'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:

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

>>> [{"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}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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