Home > database >  How to map python dictionaries key values with unequal length of items?
How to map python dictionaries key values with unequal length of items?

Time:07-06

Suppose we have two dictionaries as below:

dict_a_to_b = {2:4, 6:9, 9:3}

dict_a_to_c = {2: 0.1, 6:0.2, 9: 0.8, 10:0.6, 50: 0.77, 12:0.56}

How to map these two dictionaries to make dict_c_to_b in python? The items in second dictionary is greater than items in first.

Output should be:

dict_c_to_b = {0.1:4, 0.2:9, 0.8:3}

CodePudding user response:

You can use a dictionary comprehension:

{c: dict_a_to_b[a] for a, c in dict_a_to_c.items() if a in dict_a_to_b}

Do note that dictionary values don't have to be unique. If dict_a_to_c has duplicate values, the key associated with the last one wins here, assuming it is also available as a key in dict_a_to_b.

CodePudding user response:

You can iterate for k in dict_a_to_b and select corresponding values from both dictionaries.

dict_c_to_b = {dict_a_to_c[k]: dict_a_to_b[k] for k in dict_a_to_b}
{0.1: 4, 0.2: 9, 0.8: 3}
  • Related