How can I compare 2 dictionaries?
<p>I have two dictionaries</p>

<pre><code>dict_a = {'x' : 2, 'y' : 3.5, 'z' : 4}
dict_b = {'bob' : ['x', 'y'], 'john' : ['z', 'x'], 'bill' : ['y']}
</code></pre>

<p>I want to compare the two dictionaries and create a new one with the keys from <code>dict_b</code> and values from <code>dict_a</code>if the values from <code>dict_b</code> match. I would expect to see:</p>

<pre><code>new_dict = {'bob' : [2, 3.5], 'john' : [4, 2], 'bill' : [3.5]}
</code></pre>

<p>I have tried the following code:</p>

<pre><code>for name, guess in dict_b.items():
    if guess == i in dict_a.values():
        new_dict[name].append(i)  
print(new_dict)
</code></pre>

<p>I get the error <code>NameError: name 'i' is not defined</code>but I'm not sure how to define 'i'.</p>

<p>Thanks for any help</p>

<p>This can be done with a simple dict comprehension:</p>

<pre><code>&gt;&gt;&gt; {k: [dict_a.get(x,x) for x in v] for k, v in dict_b.items()}
{'bob': [2, 3.5], 'john': [4, 2], 'bill': [3.5]}
</code></pre>

<p>This replaces values with those from <code>dict_a</code> if they exist. Otherwise, keeps those from <code>dict_b</code> (the second argument in <code>.get(x,x)</code>).</p>

<p>Alternatively, fix the original code this way:</p>

<pre><code>new_dict = {}
for name, guess in dict_b.items():
    new_dict[name] = []
    for value in guess:
        if value in dict_a:
            new_dict[name].append(dict_a[value])  
print(new_dict)
</code></pre>

python if-statement dictionary