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>

<pre><code>if guess == i in dict_a.values():
</code></pre>

<p>This does not do what you expect it to do. Python here chains the operators, so your test is equivalent to the following:</p>

<pre><code>(guess == i) and (i in dict_a.values())
</code></pre>

<p>So itâs not like executing a for loop here where you iterate a variable <code>i</code> in the dictionary values.</p>

<p>Furthermore, you actually need to collect the values from those multiple keys, so what you would want to do here is the following:</p>

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

<p>Then, you can also use list comprehensions to shorten this:</p>

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

<p>And finally, you could even combine this with a dict comprehension:</p>

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

python if-statement dictionary