Chin Lim
Chin Lim

Reputation: 143

Python 3 - intersection of multiple dictionary key

below is my code, any one can help me to optimize the process by using python 3 build-in library function ?

Dict1 = {'ky1':1, 'ky2':2,'ky_3':3}
Dict2 = {'ky1':4, 'ky2':5,'ky_4':6}
Dict3 = {'ky2':7, 'ky3':8,'ky_5':9}
D = [Dict1,Dict2,Dict3]
Keys_list = []
for i in D:
   tmp = list(i.keys())
   Keys_list.append(tmp)
Output = list(set.intersection(*map(set,Keys_list)))

My Dict1, Dict2, Dict3 is large dictionary
thanks

Upvotes: 5

Views: 4121

Answers (2)

Anand S Kumar
Anand S Kumar

Reputation: 90979

If you just want the list of all keys in all of the dictionaries, you can use dict.viewkeys() (For Python 2.7) or dict.keys() in Python 3.x , to get the dictionary view object, and then intersect them.

Example for Python 3.x -

>>> Dict1 = {'ky1':1, 'ky2':2,'ky_3':3}
>>> Dict2 = {'ky1':4, 'ky2':5,'ky_4':6}
>>> Dict3 = {'ky2':7, 'ky3':8,'ky_5':9}
>>>
>>> Dict1.keys() & Dict2.keys() & Dict3.keys()
{'ky2'}
>>> list(Dict1.keys() & Dict2.keys() & Dict3.keys())
['ky2']

For Python 2.7 use Dict1.viewkeys() , etc, instead of .keys() .


If you have a list of dictionaries , one way to do this in one line using functools.reduce() function, would be -

>>> ld = [{'ky1':1, 'ky2':2,'ky_3':3},{'ky1':4, 'ky2':5,'ky_4':6},{'ky2':7, 'ky3':8,'ky_5':9}]
>>> res = list(reduce(lambda x, y: x & y.keys() , ld))
>>> res
['ky2']

Similar logic, using for loop -

>>> ld = [{'ky1':1, 'ky2':2,'ky_3':3},{'ky1':4, 'ky2':5,'ky_4':6},{'ky2':7, 'ky3':8,'ky_5':9}]
>>> res = ld.pop()
>>> for d in ld:
...     res = res & d.keys()
...
>>> list(res)
['ky2']

Upvotes: 3

Renae Lider
Renae Lider

Reputation: 1024

If I understood your question properly, you're looking for the intersecting keys amongst all three dictionaries, right?

If that is the case, you only need to iterate over one of them, and the process is simple.

isect = [i for i in Dict1 if all(i in d for d in (Dict1,Dict2,Dict3))]

print(isect)

The list comprehension iterates over one dict, and each item is looked up in all three dicts. If it is present, it will be added to the list. You'll get:

['ky2']

as the output.

Upvotes: 0

Related Questions