如何在一本字典中找到在另一个字典中没有对应字的密钥?(How do I find the keys in one dictionary that do not have a counterpart i

编程入门 行业动态 更新时间:2024-10-24 22:21:58
如何在一本字典中找到在另一个字典中没有对应字的密钥?(How do I find the keys in one dictionary that do not have a counterpart in another dictionary?)

在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}

更多推荐

本文发布于:2023-08-07 11:34:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464270.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字典   密钥   一本   中找到   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!