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:

>>> P = dict(zip('a b c d'.split(),[1,2,3,4]))
>>> E = dict(zip('a b e f'.split(),[6,7,8,9]))
>>> set(P)-set(E)
{'d', 'c'}
>>> set(E)-set(P)
{'f', 'e'}

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:

>>> {k:v for k,v in P.items() if k not in E}
{'d': 4, 'c': 3}
>>> {k:v for k,v in E.items() if k not in P}
{'f': 9, 'e': 8}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement