Compare two dictionaries on keys and return keys and items

If I have two dictionaries:

{MyKey1 : MyValue1, MyKey2 : MyValue2, MyKey3 : MyValue3, MyKey4 : MyValue4}
{MyKey1 : MyValue1, MyKey2 : MyValue2}

I want to compare for keys, not values, and return the differences as a dictionary, in this case:

{MyKey3 : MyValue3, MyKey4 : MyValue4}

I know I can loop through, but was wondering if there is a more pythonic way. The reason I want to use keys, is they will always be the same across dictionaries, the values might not.

It sort of depends on what your expectations are.

Given the following…

my_dict = {'One': 1, 'Two': 2}
my_dict_two = {'One': 'one', 'Three': 3}

Then the following code would get you the keys which are in my_dict_two, but which are not in my_dict.

list(set(my_dict_two) - set(my_dict))

This is only half of the available information, however, because there are keys in my_dict which are not in my_dict_two. If you want to get all keys which are not accounted for in both dictionaries, then you need to include the “other” direction:

list(set(my_dict_two) - set(my_dict)) + list(set(my_dict) - set(my_dict_two))
['Three', 'Two']

Is this pythonic enough? :slight_smile:

diff = { k : mainDict[k] for k in set(mainDict) - set(secDict) }

I only need to compare one way, main to secondary. The keys will always be the same, since the secondary dictionary is derived from the main. I was having issues finding a good way to have a result as a dictionary with both keys and values.


Yes, but if all you’re interested in is the difference in keys, do you need the values as well? It seems like
you’re setting up a dictionary of differences WITH the values when you already said you just needed to know about the missing keys. If you need the differences and their values, then what you supplied should work and is better than looping over the dictionaries.

I want the compare on keys, but return both as a dictionary. I tested and what I posted seems to do the trick.