简体   繁体   English

从另一个字典列表中按键更新字典列表

[英]update list of dict by key from another list of dict

I have two lists of dicts:我有两个字典列表:

a = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}]
b = [{'id': 1, 'name': 'test'}, {'id': 2, 'name': 'test'}, {'id': 3, 'name': 'test'}, {'id': 4, 'name': 'test'}, {'id': 5, 'name': 'test'}]

I need to update the dicts in a with the key 'name' from the dicts of b by key 'id' .我需要通过键'id'使用b的字典中的键'name'更新a中的字典。 Result which I expected:我预期的结果:

a = [{'id': 1, 'name': 'test'}, {'id': 2, 'name': 'test'}, {'id': 3, 'name': 'test'}, {'id': 4, 'name': 'test'}]

How can I do it?我该怎么做?

You should first create an "index" of the dictionaries in list b , then you can update list a using a list comprehension:您应该首先在列表b中创建字典的“索引”,然后您可以使用列表推导更新列表a

ib = { d["id"]:d for d in b }
a  = [ {**d,**ib.get(d["id"],{})} for d in a ]

It's probably a filter process, get a list of filter scope first and do the filter这可能是一个filter过程,首先获取过滤器列表 scope 并进行过滤

a = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}]
b = [{'id': 1, 'name': 'test'}, {'id': 2, 'name': 'test'}, {
    'id': 3, 'name': 'test'}, {'id': 4, 'name': 'test'}, {'id': 5, 'name': 'test'}]
print(list(filter(lambda x: x['id'] in [i['id'] for i in a], b)))

Result:结果:

[{'id': 1, 'name': 'test'}, {'id': 2, 'name': 'test'}, {'id': 3, 'name': 'test'}, {'id': 4, 'name': 'test'}]

Converting a to a set of ids for membership lookups could be a solution as well:a转换为一组用于成员查找的 id 也可能是一种解决方案:

ids = {x["id"] for x in a}

result = [x for x in b if x["id"] in ids]

print(result)
# [{'id': 1, 'name': 'test'}, {'id': 2, 'name': 'test'}, {'id': 3, 'name': 'test'}, {'id': 4, 'name': 'test'}]

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

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