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
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With