[英]count how many times keys repeat between dictionaries in python
How do I check to see how many times the keys in one dict1
exist in dict2
. 我如何检查,看看在一个按键多少次dict1
中存在dict2
。 If the keys of dict1
exist in dict2
a variable, val
, with an initial value of 4
should be subtracted based on how many times the keys are found. 如果dict1
的键存在于dict2
,则应根据找到键的次数减去初始值为4
的变量val
。
For example dict1
looks like this 例如, dict1
看起来像这样
print dict1
{(2, 0): 3, (3, 1): 0, (1, 1): 2, (2, 2): 1}
and dict2
looks like this 和dict2
看起来像这样
print `dict2`
{(2, 0): 323, (3, 1): 32, (10, 10): 21, (20, 2): 100}
Since there are two repeat keys between the dicts, val
should be equal to 2
. 由于dicts之间有两个重复键, val
应该等于2
。
if dict2
looks identical to dict1
, then val
should be 0
. 如果dict2
看起来与dict1
,然后val
应该是0
。
Also, dict1
will always be the same size, but dict2
can get quite large, so a fast lookup method would be ideal. 此外, dict1
将始终具有相同的大小,但dict2
可能会变得非常大,因此快速查找方法将是理想的。 Lastly, the values of dicts here don't really mean anything. 最后,这里的dicts值并不意味着什么。
Using set intersection: 使用集合交集:
d1 = {(2, 0): 3, (3, 1): 0, (1, 1): 2, (2, 2): 1}
d2 = {(2, 0): 323, (3, 1): 32, (10, 10): 21, (20, 2): 100}
sd1 = set(d1.keys())
sd2 = set(d2.keys())
len(sd1.intersection(sd2))
Edit: Because key views are already set-like, so you can do d1.keys() & d2.keys()
directly. 编辑:因为键视图已经设置,所以你可以直接执行d1.keys() & d2.keys()
。 Note that .keys()
is a very cheap call because it simply provides an alternative interface to the existing dict structure (Credits to @PM2RING in the comments). 请注意, .keys()
是一个非常便宜的调用,因为它只是为现有的dict结构提供了一个替代接口(注释中的@ PM2RING的Credits)。
Since dict_keys are already set-like , you can simply use 由于dict_keys 已经设置好了 ,你可以简单地使用
len(dict1.keys() & dict2.keys())
That is for Python 3. In Python 2, the equivalent view object is dict.viewkeys()
, which you'd use similarly. 这适用于Python 3.在Python 2中,等效的视图对象是dict.viewkeys()
,您可以使用它。
len(dict1.viewkeys() & dict2.viewkeys())
Make sets out of the list of keys in each dict. 从每个字典中的键列表中设置集合。 Find the intersection and union of those sets. 找到这些集合的交集和并集。 union - intersection
gives you the set of differences. union - intersection
为您提供了一组差异。 If that's 0, then you return 0; 如果那是0,那么你返回0; otherwise, return the size of the intersection. 否则,返回交叉点的大小。
This will work in Python 2 and 3: len(set(dict1).intersection(dict2))
这将在Python 2和3中起作用: len(set(dict1).intersection(dict2))
In [1]: dict1 = {(2, 0): 3, (3, 1): 0, (1, 1): 2, (2, 2): 1}
In [2]: dict2 = {(2, 0): 323, (3, 1): 32, (10, 10): 21, (20, 2): 100}
In [3]: len(set(dict1).intersection(dict2))
Out[3]: 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.