Question: 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?

In other words I want a simplest way to calculate the following:

```
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

```

I've managed to simplify it to this:

```
commonkeys = set(dict1).intersection(dict2)
return all(dict1[key] == dict2[key] for key in commonkeys)

```

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 `commonkeys` above is necessary, it would only need to be done once.)

Answer: 
What about the following?

```
return all(dict2[key] == val for key, val in dict1.iteritems() if key in dict2) 

```

Or even shorter (although it possibly involves a few more comparisons):

```
return all(dict2.get(key, val) == val for key, val in dict1.iteritems())

```
Try this

```
dict((k, dict1[k]) for k in dict1.keys() + dict2.keys() if dict1.get(k) == dict2.get(k))

```

O(m + n) comparisons.

If you want a true/false result put a simple check on the above result. If not none return true