[英]Return key associated with min value of a dict if min key is not in set
I have a dictionary and a set. 我有一本字典和一套。 I want to return the key associated with the minimum value if that key is not already in the set without creating a second dictionary used to delete items that are already in the set.
如果该键尚未在集合中,则我想返回与最小值关联的键,而无需创建第二个用于删除该集合中已存在项的字典。
Example: I have dictionary 例子:我有字典
d = {1:10, 2:20, 3:30, 4:40}
and a set 和一套
s = set([1,2])
It should return 3 它应该返回3
Use the set operations to subtract the set s
from the set of keys of d
, then use min
with key=d.get
to get the remaining key with the smallest value: 使用set操作从
d
的键集中减去set s
,然后将min
与key=d.get
一起使用,以获取具有最小值的其余键:
d = {1:10, 2:20, 3:30, 4:40}
s = set([1,2])
print min(set(d) - s, key=d.get)
prints 3
版画
3
If the result must be None
when no key was found use: 如果在没有找到键的情况下结果必须为
None
,请使用:
q = set(d) - s
print min(q, key=d.get) if q else None
Rather than the ValueError
from min
. 而不是
min
的ValueError
。
You could use min
with generator expression that returns keys not in s
and key parameter that gets the value from d
: 您可以将
min
与生成器表达式结合使用,该表达式返回不在s
键和从d
获取值的键参数:
>>> d = {1:10, 2:20, 3:30, 4:40}
>>> s = set([1,2])
>>> min((k for k in d if k not in s), key=d.get)
3
Above approach wouldn't create any intermediate containers. 上面的方法不会创建任何中间容器。 In case there's a possibility that
s
matches keys from d
default value can be used: 如果有可能
s
匹配d
默认值的键,则可以使用:
>>> d = {1:10, 2:20, 3:30, 4:40}
>>> s = set([1,2,3,4])
>>> min((k for k in d if k not in s), key=d.get, default=-1)
-1
Set operations work nicely here. 设置操作在这里很好地工作。
d = {1:10, 2:20, 3:30, 4:40}
s = set([1,2])
def find_min(d, s):
keys = set(d)
difference = keys-s
return min(difference) if difference else None
>>> print find_min(d, s)
3
alternatively, you could have difference = filter(lambda e: e not in s, d)
或者,您可能会有
difference = filter(lambda e: e not in s, d)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.