Fastest way to merge 2 dictionaries, if one dict's key equals to the other dict's values?
<p>Suppose I have 2 dictionaries</p>

<pre><code>dict1 = {(1,1,1) : ('abc'), (2,2,2) : ('def')} 
dict2 = {('abc') : (1,2,3), ('def') : (4,5,6)}
</code></pre>

<p>What is the fastest way to produce a dict 3 such that</p>

<p><code>dict3 = {(1,1,1):(1,2,3), (2,2,2):(4,5,6)}</code>?</p>

<p>You can use a dictionary comprehension:</p>

<pre><code>dict1 = {(1,1,1) : ('abc'), (2,2,2) : ('def')} 
dict2 = {('abc') : (1,2,3), ('def') : (4,5,6)}
dict3 = {k: dict2[dict1[k]] for k in dict1}

&gt;&gt;&gt; print dict3
{(2, 2, 2): (4, 5, 6), (1, 1, 1): (1, 2, 3)}
</code></pre>

<p>This iterates over the <em>keys</em> of <code>dict1</code> and, using the corresponding <em>value</em> from <code>dict1</code> as a key, looks up the value in <code>dict2</code>. The key from <code>dict1</code> and the value from <code>dict2</code> are then combined to produce a new dictionary.</p>

<p>Note that, in Python 2, this should be slightly faster then using <code>dict1.items()</code> because that will build a temporary list. Similarly, iterating over <code>dict1.iteritems()</code> returns an iterator which has to be created, but that is neglible. Iterating directly over a dictionary's keys also incurs minimal overhead.</p>

python dictionary