Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 471
Chin Lim Avatar asked Oct 20 '22 05:10

Chin Lim


1 Answers

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']
like image 99
Anand S Kumar Avatar answered Oct 21 '22 22:10

Anand S Kumar