Alen thomas Alen thomas - 21 days ago 5
Python Question

Create a dictionary from two dictionaries using the key from one with the value of the other

I have 2 dictionaries:

d1 = {'a':'python','b':'java','c':'c++','d':'js',........}
d2 = {'1':'a','2':'b','4':'d','3':'c',........}


I need to make new dictionary using both, second dict value should be key of new dict and first dict values should be value of new dict dict, like:

result = {'1':'python','2':'java','3':'c++','4':'js',........}


I try to do it like this :

d2_rev = {j:i for i,j in d2.items()}
result = {i:d2_rev[i] for i,j in d2_rev }


I am getting correct output accept I have very large dictionaries and execution is taking more time. Is there anything I can do to improve the speed of this code?

Answer

I don't know why you're creating an additional (switched) dictionary, you could just use:

result = {i: d1[j] for i, j in d2.items()}

and cut down memory and speed by not creating the additional dict. The value of the one dict is the key in the other, just get it directly.

Other than that; I don't think, in Python alone, you'd be able to get better results.