简体   繁体   中英

How to find common occurrences of dictionary in a list of list of dictionaries

I have a list of list of dictionaries and I want to find the common dictionaries between the two list.

Eg:

dict_list = [[{'1' : 1,'2' : 2, '3' :3}, {'6' : 6,'5' : 5, '4' : 4}],  
             [{'1' : 1,'2' : 2, '3' :3}, {'7' : 7,'8' : 8, '9' : 9}]]

The result should be [{'1' : 1,'2' : 2, '3' :3}]

I tried using set intersections but dictionaries are unhashable in python.

How to solve this?

A list comprehension could work here:

>>> [x for x in dict_list[0] if x in dict_list[1]]
[{'1': 1, '2': 2, '3': 3}]

But this is not a very general solution, since it assumes only two nested lists are exististent.

A more general solution would be to count the occurences with collections.Counter() , and storing the dictionary items() with hashable/immutable types such as frozenset() or tuple() . Then all you need to do is filter the occurences that count more than 1.

Example:

>>> from itertools import chain
>>> from collections import Counter
>>> [dict(k) for k, v in Counter(frozenset(x.items()) for x in chain.from_iterable(dict_list)).items() if v > 1]
[{'1': 1, '2': 2, '3': 3}]

Which is very similar to the approach @Chris_Rands posted in the comments.

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