python - 查找具有最大属性值的对象的键

标签 python dictionary

我有这样的字典。

d = {
    'a' : {'c' : 1, 'h' : 2},
    'b' : {'c' : 3, 'h' : 5},
    'c' : {'c' : 2, 'h' : 1},
    'd' : {'c' : 4, 'h' : 1}
}

我需要获取具有最高 c + h 值的项的键。

我知道在这种情况下你可以获得具有最高值(value)的项目的键:

d = { 'a' : 1, 'b' : 2, 'c' : 3 }
max( d, key = d.get ) # 'c'

在我的案例中是否可以使用 max 函数?

最佳答案

你可以为 key 指定你自己的函数,它可以做一些奇特的事情,比如获取 ch 的值并将它们相加.例如使用内联 lambda:

>>> max(d, key=lambda x: d[x]['c'] + d[x]['h'])
'b'

关于python - 查找具有最大属性值的对象的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20291392/

相关文章:

python - 打开文本文件并在 Python 中获取冒号后面的数据

algorithm - splay 树(自平衡树)背后的直觉

jquery - Python Flask 获取json数据显示

python - Numpy - 获得相邻元素之间的乘法差异

Python,字典的校验和

python - 多个交互式 matplotlib 在 python 2.7 和 3.6 中的行为不同

java - 从 Treemap 获取带有 id 的对象会引发异常

Python 将特定字符串转换为字典

python - 替换原生 python 上不稳定的 Tcl/Tk

python - Python Dict 中错误消息的优先级