How can I find dict keys for matching values in two dicts?
<p>I have two dictionaries mapping IDs to values. For simplicity, lets say those are the dictionaries:</p>

<pre><code>d_source = {'a': 1, 'b': 2, 'c': 3, '3': 3}
d_target = {'A': 1, 'B': 2, 'C': 3, '1': 1}
</code></pre>

<p>As named, the dictionaries are not symmetrical.
I would like to get a dictionary of <em>keys</em> from dictionaries <code>d_source</code> and <code>d_target</code> whose values match. The resulting dictionary would have <code>d_source</code> keys as its own keys, and <code>d_target</code> keys as that keys value (in either a <code>list</code>, <code>tuple</code> or <code>set</code> format).</p>

<p>This would be The expected returned value for the above example should be the following list:</p>

<pre><code>{'a': ('1', 'A'),
 'b': ('B',),
 'c': ('C',),
 '3': ('C',)}
</code></pre>

<p>There are two somewhat <a href="http://stackoverflow.com/questions/21631951/find-matching-key-value-pairs-of-two-dictionaries">similar</a> <a href="http://stackoverflow.com/questions/11615041/how-to-find-match-items-from-two-lists">questions</a>, but those solutions can't be easily applied to my question.</p>

<p>Some characteristics of the data:</p>

<ol>
<li>Source would usually be smaller than target. Having roughly few thousand sources (tops) and a magnitude more targets.</li>
<li>Duplicates in the same dict (both <code>d_source</code> and <code>d_target</code>) are not too likely on values.</li>
<li>matches are expected to be found for (a rough estimate) not more than 50% than <code>d_source</code> items.</li>
<li>All keys are integers.</li>
</ol>

<p>What is the best (performance wise) solution to this problem?
Modeling data into other datatypes for improved performance is totally ok, even when using third party libraries (i'm thinking <a href="http://www.numpy.org/" rel="nofollow">numpy</a>)</p>

<p>This maybe "cheating" in some regards, although if you are looking for the matching values of the keys regardless of the case sensitivity then you might be able to do:</p>

<pre><code>import sets

aa = {'a': 1, 'b': 2, 'c':3}
bb = {'A': 1, 'B': 2, 'd': 3}

bbl = {k.lower():v for k,v in bb.items()}

result = {k:k.upper() for k,v in aa.iteritems() &amp; bbl.viewitems()}
print( result )
</code></pre>

<p><strong>Output:</strong></p>

<pre><code>{'a': 'A', 'b': 'B'}
</code></pre>

<p>The <code>bbl</code> declaration changes the <code>bb</code> keys into lowercase (it could be either <code>aa</code>, or <code>bb</code>). </p>

<p><sub>* I only tested this on my phone, so just throwing this idea out there I suppose... Also, you've changed your question radically since I began composing my answer, so you get what you get.</sub> </p>

python dictionary optimization