首页 > 解决方案 > 循环遍历 2 个字典列表

问题描述

我有这 2 个字典列表如果list1list2.

list1=[{'name':'A','color':'1'},
       {'name':'B','color':'2'}]

list2=[{'name':'A','color':'3'},
       {'name':'C','color':'1'}]

for item in list1:
    for ii in list2:
        if item['name'] != ii['name']: 
            print item['name']

我得到的输出是

A
B
B

我希望它能够打印B,因为 list2 中没有 b。不知道我做错了什么......任何帮助将不胜感激。

谢谢

标签: pythondictionary

解决方案


目前在您的双 for 循环中,您打印list1 和 list2 的两个元素item['name']之间的不匹配any,这不是您想要的。

相反,您可以将两个列表中的名称转换为集合并获取集合差异

list1=[{'name':'A','color':'1'},
       {'name':'B','color':'2'}]

list2=[{'name':'A','color':'3'},
       {'name':'C','color':'1'}]

#Iterate through both lists and convert the names to a set in both lists
set1 = {item['name'] for item in list1}
set2 = {item['name'] for item in list2}

#Take the set difference to find items in list1 not in list2
output = set1 - set2
print(output)

输出将是

{'B'}

推荐阅读