如何找到两个字典列表之间的区别? [英] How to find the difference between two lists of dictionaries?

查看:171
本文介绍了如何找到两个字典列表之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个字典列表,我想找到它们之间的区别(即第一个列表中存在的但不是第二个列表,第二个列表中存在什么,而不是第一个列表)。



问题是它是一个字典列表

  a = {{'a':'1'},{'c':'2'}] 
b = [{'a':'1'},{'b':'2'}]

set(a) - set(b)

结果

  TypeError:unhashable type:'dict'

所需结果:

  {'c':'2'} 

如何实现?

解决方案

p>您可以使用运算符中的来查看是否在列表中

  a = [{'a':'1'},{'c':'2'}] 
b = [{'a':'1'},{'b':'2' }]

>>>一个
中的{'a':'1'} True
>>> {'a':'1'} in b
True

>>> [我为我,如果我不在b]
[{'c':'2'}]


I have two lists of dictionaries and I'd like to find the difference between them (i.e. what exists in the first list but not the second, and what exists in the second list but not the first list).

The issue is that it is a list of dictionaries

a = [{'a': '1'}, {'c': '2'}]
b = [{'a': '1'}, {'b': '2'}]

set(a) - set(b)

Result

TypeError: unhashable type: 'dict'

Desired Result:

{'c': '2'}

How do I accomplish this?

解决方案

You can use the in operator to see if it is in the list

a = [{'a': '1'}, {'c': '2'}]
b = [{'a': '1'}, {'b': '2'}]

>>> {'a':'1'} in a
True
>>> {'a':'1'} in b
True

>>> [i for i in a if i not in b]
[{'c': '2'}]

这篇关于如何找到两个字典列表之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆