在嵌套字典中查找Max

2024-09-26 22:50:16 发布

您现在位置:Python中文网/ 问答频道 /正文

d = {
    "local": {
        "count": 1,
        "health-beauty": {
            "count": 1,
            "tanning": {"count": 1}
        }
    },
    "nationwide": {"count": 9.0},
    "travel": {"count": 0}
}    

在这个例子中,"nationwide"是最大的。在

下面的代码使附加到脚本更容易:

^{pr2}$

Tags: 代码脚本localcount例子beautyhealthtravel
2条回答
>>> max(d, key=lambda x: d[x]['count'])
'nationwide'

这对于嵌套字典应该有效:

def find_max(d, name=None):
    return max((v, name) if k == "count" else find_max(v, k) for k, v in d.items())

>>> find_max(d)
(9.0, 'nationwide')

相关问题 更多 >

    热门问题