This is what I've got so far: { k1:v2 for (k1,v1) in d1 for (k2,v2) in d2 if v1 == k2 }
Two things you should note:
1) When you use the for-in loop directly on the dict:
for (k1, v1) in some_dict:
python loops over keys in a dict, i.e. this for-in loop is equivalent to:
for (k1, v1) in some_dict.keys()
But you tell python that each loop returns through the loop, (k1, v1), and python only returns every key through the loop. So this is a mistake. You can fix this by writing:
for (k1, v1) in some_dict.items()
The items () function returns two tuples: (key, value) every time through the loop.
2) Suppose you have this data:
data = [ [1, 2, 3], ['a', 'b', 'c'] ]
To iterate over each of the six values, itβs natural to write:
results = [x for x in inner_array for inner_array in data]
But this causes an error:
Traceback (most recent call last): File "1.py", line 5, in <module> results = [x for x in inner_array for inner_array in data] NameError: name 'inner_array' is not defined
To make it work, loops should be written backwards:
results = [x for inner_array in data for x in inner_array] print results --output:-- [1, 2, 3, 'a', 'b', 'c']
I think the easiest way to remember this is: the loops are in the same order as if you wrote them without understanding the list:
results = [] for inner_array in data: for x in inner_array: results.append(x)
Personally, I would like to see that this has changed in python, so inside the list / dict / set definition you are working from the inside out, as you wrote it. In any case, this is what your code looks like with changes:
d1 = {1:'a',2:'b',3:'c'} d2 = {'a':'A','b':'B','c':'C'} results = { k1: v2 for (k2,v2) in d2.items() for (k1,v1) in d1.items() if v1 == k2 } print results --output:-- {1: 'A', 2: 'B', 3: 'C'}