Home > Blockchain >  How to map python dictionary key values to each other?
How to map python dictionary key values to each other?

Time:07-01

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}

How to map these two dictionaries to make dict_c_to_b in python?

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

CodePudding user response:

Use a dict comprehension - something like this:

dict_a_to_b = {2:4, 6:9, 9:3}
dict_a_to_c = {2: 0.1, 6:0.2, 9: 0.8}

result = {v: dict_a_to_b[k] for k, v in dict_a_to_c.items()}

print(result)  #-> {0.1: 4, 0.2: 9, 0.8: 3}

If you know the keys in both dict_a_to_b and dict_a_to_c appear in the same order, you can also use zip and just use the values on both dict objects:

result = dict(zip(dict_a_to_c.values(), dict_a_to_b.values()))

print(result)  #-> {0.1: 4, 0.2: 9, 0.8: 3}
  • Related