在Python中,如何在一个字典中找到没有另一个字典中对应字符的键? 实际的问题是,我有一本关于注册人员的字典和一本日常参与的字典,我试图找到注册但未参与的人员,或者在注册字典中,而不是在参与字典中。
在Python食谱中,我发现了交叉点注册和参与的好代码,或者两个字典的交集:
print "Intersection: ", filter(enrollments.has_key, participation.keys())
但我无法弄清楚如何将这种逻辑延伸到正面(?)的情况。 我试图把一个不在之前参加.keys(),但我得到一个错误。 有没有办法将过滤器中的逻辑扩展到我的问题或其他方式来完成?
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?
最满意答案
使用按键上的设置找出不同之处:
>>> 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'}另外,你可以使用字典理解。 它们是跨越字典映射函数和/或过滤内容的一种方式。 该语法意味着为每个键和字典项中键的值不在另一个字典中的键返回键值对:
>>> {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}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. They are 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}更多推荐
发布评论