Comparing dictionaries on shared keys only
<p>I have two dictionaries with some shared keys, and some different ones. (Each dictionary has some keys not present in the other). What's a nice way to compare the two dictionaries for equality, as if only the shared keys were present?</p>

<p>In other words I want a simplest way to calculate the following:</p>

<pre><code>commonkeys = set(dict1).intersection(dict2)
simple1 = dict((k, v) for k,v in dict1.items() if k in commonkeys)
simple2 = dict((k, v) for k,v in dict2.items() if k in commonkeys)
return simple1 == simple2
</code></pre>

<p>I've managed to simplify it to this:</p>

<pre><code>commonkeys = set(dict1).intersection(dict2)
return all(dict1[key] == dict2[key] for key in commonkeys)
</code></pre>

<p>But I'm hoping for an approach that doesn't require precalculation of the common keys. (In reality I have two lists of dictionaries that I'll be comparing pairwise. All dictionaries in each list have the same set of keys, so if a computation like <code>commonkeys</code> above is necessary, it would only need to be done once.)</p>