Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: comprehension to compose two dictionaries

Tags:

python

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.

like image 746
Roma149 Avatar asked Jul 24 '13 23:07

Roma149


2 Answers

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?

like image 113
Peter DeGlopper Avatar answered Oct 12 '22 10:10

Peter DeGlopper


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'}
like image 38
poke Avatar answered Oct 12 '22 10:10

poke