I'm trying to write a comprehension that will compose two dictionaries in the following way:
d1 = {1:'a',2:'b',3:'c'}
d2 = {'a':'A','b':'B','c':'C'}
result = {1:'A',2:'B',3:'C'}
That is, the resulting dictionary is formed from the keys of the first one and the values of the second one for each pair where the value of the first one is equal to the key of the second one.
This is what I've got so far:
{ k1:v2 for (k1,v1) in d1 for (k2,v2) in d2 if v1 == k2 }
but it doesn't work. I'm new to Python so I'm not sure whether this really makes sense. I'm using python 3.3.2 by the way.
Thanks in advance.
One way to do it is:
result = {k: d2.get(v) for k, v in d1.items()}
What behavior did you want for keys that have a value that is not in d2?
Just loop through the items of d1
and then for each element you want to put in the result don’t use the value from d1
but instead look up the new value within d2
using d1
’s value as the key:
>>> d1 = {1: 'a', 2: 'b', 3: 'c'}
>>> d2 = {'a': 'A', 'b': 'B', 'c': 'C'}
>>> d = {k: d2[v] for (k, v) in d1.items()}
>>> d
{1: 'A', 2: 'B', 3: 'C'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With