简体   繁体   中英

Remove common dictionary elements that are in 2 lists

I am trying to 'minus' out the common elements within 2 lists, however the elements within the 2 lists are dictionary.

Example:

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}]`

However as I execute the code, I got the following errors:

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

What other ways can I do to achieve the result I wanted?

这有效

[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]

It is the same as the first answer suggested, with the use of filter function:

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)

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM