Q:

How to process these 2 dictionaries to get a new dictionary in Python?

I have these 2 dictionaries;
Dict1 = {1: ('John', 37), 2: ('Tom', 23), 3: ('Tom', 19), 4: ('Jane', 58)}
Dict2 = {1: ('2',), 2: ('4',), 3: ('19',)}   

The output dictionary from processing the above 2 dictionaries is;
OutputDict = {1: ('John', 37), 2: ('Tom', 23)} 

The logic in getting OutputDict is like this;
(1) Dict1 and Dict2 must have matching keys. If not, OutputDict will discard the key:value pair from Dict1.
(2) If a matching key is found, the 2nd element in the value of Dict1 must be different from the value in Dict2. If they are the same, OutputDict will discard the key:value pair from Dict1.
How can this be programmed in Python? I am using Python 2.7.

A:

You can use a dictionary comprehension to iterate through the key-value pairs in Dict1, only keeping those key-value pairs such that (1) the key is in Dict2; and (2) the numeric value matches Dict1 and Dict2:
Demo
>>> OutputDict = { k: v for k, v in Dict1.iteritems()
                   if k in Dict2 and int(Dict2[k][0]) != v[1] }
>>> OutputDict
{1: ('John', 37), 2: ('Tom', 23)}

