1

Say, for example, we have the following dictionaries:

dict1 = {a:b, b:c}
dict2 = {b:c, c:d}

What is the most efficient way of intersecting the keys of both dictionaries?

Of course, one can use set(dict1.keys()).intersection(set(dict2.keys())), but I assume converting the dictionary to a set first is not efficient at all.

Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
Thijmen
  • 374
  • 2
  • 14

2 Answers2

9

keys is a view and has the intersection operator

dict1.keys() & dict2.keys()

Or simply

dict1.keys() & dict2
rafaelc
  • 57,686
  • 15
  • 58
  • 82
3

The dict.keys() view object supports set operations:

dict1.keys() & dict2.keys()  # equivalent to set(dict1).intersection(dict2)

However, for smaller dictionaries using a set will probably be faster:

In [1]: dict1 = {'a': 'b', 'c': 'd'}

In [2]: dict2 = {'b': 'c', 'c': 'd'}

In [3]: %timeit dict1.keys() & dict2.keys()
448 ns ± 1.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)    

In [4]: %timeit set(dict1).intersection(dict2)
330 ns ± 0.602 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Note that set.intersection() accepts any iterable as an argument, so you can just pass dict2 to it. Also, no need to call dict1.keys()as a dict object by default iterates over its keys.

Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378