我有一本字典
{0: 12, 1: 1, 2: 13, 3: 7, 4: 0}
我想找到值大于0的最高字典键。
在这种情况下,答案是3。
最好的方法是什么?
答案 0 :(得分:3)
使用genexpr过滤掉"坏"值和max
保持最高值:
# On Py2, use .iteritems() instead of .items()
max(k for k, v in mydict.items() if v > 0)
或者,如果在没有引发异常的情况下没有键符合条件,则需要有默认值:
# Py3 max has default, which makes this super-easy:
max((k for k, v in mydict.items() if v > 0), default=SOMEVALUEGOESHERE)
# Py2 doesn't have default; workaround is to catch exception and use a default (EAFP):
try:
mymax = max(k for k, v in mydict.iteritems() if v > 0)
except ValueError:
mymax = SOMEVALUEGOESHERE
# Or if you can't do that for some reason, make a listcomp instead of genexpr
# and check for at least one surviving key before calling max (LBYL)
goodkeys = [k for k, v in mydict.iteritems() if v > 0]
mymax = max(goodkeys) if goodkeys else SOMEVALUEGOESHERE
答案 1 :(得分:2)
您可以使用max
和dict.items()
执行此操作:
d = {0: 12, 1: 1, 2: 13, 3: 7, 4: 0}
highest = max(i for i,j in d.items() if j > 0)