Compare 2 dictionaries in python to create another dictionary with matching keys

3

I am programming a development and I want to compare 2 dictionaries, which in common have keys of the same name.

For example Dictionary 1 is of the form:

    dic1 = {'0': [2.4636363650000002], '6': [4.1666666650000002], '9': [4.8333333349999998], '11': [3.5000000090000012], '14': [6.6181818249999989]}

Dictionary 2 is of the form:

    dic2 = {'0': [2, 3, 4], '6': [5,6,7], '19': [4.8333333349999998], '10': [4.8333333349999998], '12': [3.5012]}

Upon seeing, the dictionary 2 coincides with the 1 the keys '0' and '6'.

My idea is to create a dictionary 3 that contains only this:

    dic3 = {'0': [2, 3, 4], '6': [5,6,7]}

What I am doing is creating lists with the keys of each dictionary, then I compare these lists and in the new dictionary I add those elements of the keys that coincide. I want to know if you know a faster and more efficient way than going through and creating lists, since there are many keys that I have.

    
asked by Jorge Ponti 20.07.2017 в 23:18
source

3 answers

6

There is a very simple method using "dictionary compressions" :

dic3 = {k:v for (k,v) in dic2.items() if k in dic1}
    
answered by 20.07.2017 / 23:30
source
3
dic3 = set(dic1).intersection(set(dic2))
    
answered by 20.07.2017 в 23:34
0

With a for cycle you can get the key of each element in the dictionary and traverse it.

for i in dic1:
   print i
   print dic1[i]
    
answered by 20.07.2017 в 23:26