比较列表包含字典项的两个列表项

时间:2017-01-10 17:33:47

标签: python

我有两个清单:

value1

我想比较这两个列表,如果b匹配,那么它将返回列表c= ['x','z'] 的所有键。我想要一个这样的结果:

cost-1

2 个答案:

答案 0 :(得分:1)

我将其读作:"从列表k中的词典d返回所有键b的列表,以便k的值d中的{}与列表a"

中某些字典中某些键的值相同
val_set = {v for d in a for v in d.values()}
output = [k for d in b for k, v in d.items() if v in val_set]
print(output)
#['x', 'z']

答案 1 :(得分:0)

您可以实现以下内容:

a = [{'1':'value1'},{'2':'value2'}]
b = [{'x':'value1'},{'y':'hello'},{'z':'value1'}]
c = [w.keys()[0] for q in a for w in b if q.values()[0] == w.values()[0]]
print(c)

输出:

['x', 'z']

相当于:

a = [{'1':'value1'},{'2':'value2'}]
b = [{'x':'value1'},{'y':'hello'},{'z':'value1'}]
c = []
for q in a:
    for w in b:
        if q.values()[0] == w.values()[0]:
            c.append(w.keys()[0])
print(c)