从两个字典创建一个新列表 [英] Create a new list from two dictionaries
本文介绍了从两个字典创建一个新列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是一个关于Python的问题。我有以下列表:
This is a question about Python. I have the following list of dictionaries:
listA = [
{"t": 1, "tid": 2, "gtm": 3, "c1": 4, "id": "111"},
{"t": 3, "tid": 4, "gtm": 3, "c1": 4, "c2": 5, "id": "222"},
{"t": 1, "tid": 2, "gtm": 3, "c1": 4, "c2": 5, "id": "333"},
{"t": 5, "tid": 6, "gtm": 3, "c1": 4, "c2": 5, "id": "444"}
]
和我想要比较的字典:
dictA = {"t": 1, "tid": 2, "gtm": 3}
我想创建一个匹配 dictA 中所有项目的列表,从 listA 并包含id字段:
I wanted to create a list of dicts that match all the items in dictA from listA and to include the "id" field as well:
listB = [
{"t": 1, "tid": 2, "gtm": 3, "id": "111"},
{"t": 1, "tid": 2, "gtm": 3, "id": "333"}
]
我试过这样做:
for k in listA:
for key, value in k.viewitems() & dictA.viewitems():
print key, value
但它匹配任何 dictA 。
推荐答案
您需要检查交集的长度只要检查,如果dct.viewitems()&对于任何交集,dictA.viewitems()
将评估为True:
You would need to check the length of the intersection, just checking if dct.viewitems() & dictA.viewitems()
would evaluate to True for any intersection :
[dct for dct in listA if len(dct.viewitems() & dictA.viewitems()) == len(dictA)]
或只是检查一个子集,如果dictA的项目是子集每个dict:
Or just check for a subset, if the items from dictA are a subset of each dict:
[dct for dct in listA if dictA.viewitems() <= dct.viewitems()]
或反转寻找 superset :
[dct for dct in listA if dct.viewitems() >= dictA.viewitems()]
这篇关于从两个字典创建一个新列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文