1

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?

letsintegreat
  • 3,328
  • 4
  • 18
  • 39
Perseus14
  • 467
  • 1
  • 6
  • 19

1 Answers1

4

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.

RoadRunner
  • 25,803
  • 6
  • 42
  • 75
  • 1
    The main point here is that even though dictionaries are not hashable they are comparable. [More about comparing dictionaries in python](https://stackoverflow.com/questions/4527942/comparing-two-dictionaries-in-python). – sophros Nov 14 '18 at 11:01