Skip to content
Advertisement

How do I find the keys in one dictionary that do not have a counterpart in another dictionary?

In Python, how do I find the keys in one dictionary that do not have a counterpart in another dictionary? The practical problem is that I have a dictionary of people that enrolled and a dictionary with their daily participation and I am trying to find the people that enrolled but did not participate, or are in the enrollments dictionary and not in the participation dictionary.

In the Python cookbook I found good code for the intersection enrollments and participation, or the intersection of the two dictionaries:

print "Intersection: ", filter(enrollments.has_key, participation.keys())

But I can’t figure out how to extend this logic to the obverse (?) case. I have tried putting a not in front of participation.keys() but I get an error. Is there a way to extend the logic in the filter to my problem or another way to approach it altogether?

Advertisement

Answer

Use sets on the keys to find the difference:

JavaScript

Also, you can use a dictionary comprehension. It is a way to map a function across a dictionary, and/or filter the contents. The syntax means to return the key:value pair for each key and value in the dictionary’s items where the key is not in another dictionary:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement