在嵌套字典中查找最大值

时间:2012-10-10 23:14:50

标签: python dictionary

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

在这种情况下,"nationwide"是最大的。

代码如下所示,以便更容易附加到脚本:

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

2 个答案:

答案 0 :(得分:12)

>>> max(d, key=lambda x: d[x]['count'])
'nationwide'

答案 1 :(得分:1)

这适用于嵌套字典:

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')