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}
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}
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 have extra keys in dict_a_to_c
that don't show up in the other object, you can use an if
condition to check if the key exists first:
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}result = {v: dict_a_to_b[k] for k, v in dict_a_to_c.items()if k in dict_a_to_b}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}