删除2个列表中的常用字典元素

时间:2017-12-02 22:11:19

标签: python

我试图“减去”2个列表中的公共元素,但是2个列表中的元素是字典。

示例:

list_dict_01 = [{'aaa':123}, {'bbb':234}, {'ccc':234}, {'ddd':456}]
list_dict_02 = [{'bbb':234}, {'ddd':456}]

res = list(set(list_dict_01)^set(list_dict_02))
# Expected output : `[{'aaa':123}, {'ccc':234}]`

然而,当我执行代码时,我收到以下错误:

# Error: unhashable type: 'dict'
# Traceback (most recent call last):
#   File "<maya console>", line 4, in <module>
# TypeError: unhashable type: 'dict' # 

我可以采取哪些其他方式来达到我想要的效果?

2 个答案:

答案 0 :(得分:1)

这有效

[item for item in list_dict_01 if not item in list_dict_02]+[item for item in list_dict_02 if not item in list_dict_01]

答案 1 :(得分:1)

与建议的第一个答案相同,使用filter函数:

list_dict_01 = [{'aaa':123}, {'bbb':234}, {'ccc':234}, {'ddd':456}]
list_dict_02 = [{'bbb':234}, {'ddd':456}]

res = list(filter(lambda i: not i in list_dict_01, list_dict_02)) + list(filter(lambda i: not i in list_dict_02, list_dict_01))
print(res)

输出:

[{'aaa': 123}, {'ccc': 234}]