我有两个 python 字典列表。我想使用键值“fruit”根据 list1 和 list2 之间的差异创建一个新的相似词典列表。两个列表中的词典都不相同。
list1 = [
{'fruit': 'apple', 'amt': '1'},
{'fruit': 'banana', 'amt': '2'},
{'fruit': 'cherry', 'amt': '3'},
{'fruit': 'date', 'amt': '4'},
{'fruit': 'elderberry', 'amt': '5'},
]
list2 = [
{'fruit': 'date', 'amt': '6'},
{'fruit': 'elderberry', 'amt': '7'},
]
list3 = [some kind of python list comprehension]
print(list3)
{'fruit': 'apple', 'amt': '1'}
{'fruit': 'banana', 'amt': '2'}
{'fruit': 'cherry', 'amt': '3'}
这有点低效,但可以检查。
def find_dif(l1, l2, check_value):
l3 = l1
l4 = []
for i in l1:
for z in l2:
if i[check_value] == z[check_value]:
l4.append(i)
for x in l4:
l3.remove(x)
return l3
它接受两个字典列表,然后根据另一个列表检查每个值。然后它从第一个列表中弹出这些值然后返回它。 编辑:它返回第一个列表中的数量。