[英]How do I find common items from Python dictionary values?
Say, I have a dictionary D
: 说,我有一本字典
D
:
D = {'A': {1, 2, 3}, 'B': {2, 4, 5}, 'C': {1, 2, 7}}
Now I want to have all common items from D
's values, which would be 2. I tried to use set.intersection
but it did not work out. 现在我希望得到
D
的值中的所有常用项,这将是2.我尝试使用set.intersection
但它没有成功。
Simply, use intersection
method of set
: 简单地说,使用
set
intersection
方法:
>>> set.intersection(*D.values())
{2}
D.values()
will return a list of your dictionary values which are already sets, then *D.values()
will unpack this list and pass it to intersection
method of set
class D.values()
将返回已经设置的字典值列表,然后*D.values()
将解压缩此列表并将其传递给set
类的intersection
方法
For the sake of variety, you could also use reduce()
: 为了多样性,您还可以使用
reduce()
:
>>> D = {'A': {1, 2, 3}, 'B': {2 ,4, 5}, 'C': {1, 2, 7}}
>>> reduce(lambda x, y: x & y, D.values()) # or use operator.and_ instead of lambda
{2}
reduce()
is a built-in function in Python 2.x, but needs to be imported from the functools
module in Python 3.x. reduce()
是Python 2.x中的内置函数,但需要从Python 3.x中的functools
模块导入。
If you are only looking for common values in each dictionary and not looking for a value that is in each dict then the following code will work! 如果您只是在每个字典中查找常用值而不是查找每个字典中的值,那么以下代码将起作用! Not saying that this is the fastest or the best approach, but it works!
不是说这是最快或最好的方法,但它有效! Returns a list of all duplicate values across the embedded dicts!
返回嵌入式dicts中所有重复值的列表!
def findCommon(data):
flipped = {}
out = []
for i in data:
for value in data[i]:
if value not in flipped:
flipped[value] = [i]
else:
flipped[value].append(i)
for i in flipped:
if len(flipped[i]) > 1:
out.append(i)
return out
If you go with reduce
the most efficient way is to use operator.and_
如果你使用
reduce
,最有效的方法是使用operator.and_
from functools import reduce
from operator import and_
D = {'A': {1, 2, 3}, 'B': {2, 4, 5}, 'C': {1, 2, 7}}
print(reduce(and_, D.values()))
But set.intersection
will be hard to beat: 但是
set.intersection
很难被击败:
In [89]: from functools import reduce
In [90]: from operator import and_
In [91]: timeit reduce(lambda x, y: x & y, D.values())
1000 loops, best of 3: 221 µs per loop
In [92]: timeit reduce(and_,D. values())
10000 loops, best of 3: 170 µs per loop
In [93]: timeit set.intersection(*D.values())
10000 loops, best of 3: 155 µs per loop
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.