Python-查找值大于零的最高字典键

标签 python dictionary

我有一本字典

{0: 12, 1: 1, 2: 13, 3: 7, 4: 0}

我想找到值大于0的最高字典键。

在本例中,答案是 3。

最好的方法是什么?

最佳答案

使用geneexpr过滤掉“坏”值,并使用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

关于Python-查找值大于零的最高字典键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40088576/

相关文章:

python - 如何在 Python 中将一个 SWIG 包装的 C 结构从一种类型转换为另一种类型?

python - 确保所有机器上的所有代码都相同 - python mpi

python - Pydantic 字典列表通过其键转换为单个字典

c++ - 使用空的 weak_ptr 作为参数调用 map::count 是否安全?

dictionary - Cassandra 映射可以保留 null 值

python - 在 Snakemake 参数部分使用特殊符号

Python:在map函数中调用方法

python - 如何交换字典中的两个随机值?

scala - Maps 中的 "get"方法是否具有 Scala 中的默认值?

python - 重用现有的 numpy 数组还是创建一个新数组?