Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Max in Nested Dictionary

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

In this instance "nationwide" is the largest.

Code is below to make it easier to attach to scripts:

d = {'travel': {'count': 0}, 'local': {'count': 1, 'health-beauty': {'count': 1, 'tanning': {'count': 1}}}, 'nationwide': {'count': 9.0}}
like image 721
AlexZ Avatar asked Oct 10 '12 23:10

AlexZ


2 Answers

>>> max(d, key=lambda x: d[x]['count'])
'nationwide'
like image 145
JBernardo Avatar answered Sep 23 '22 21:09

JBernardo


This should work for nested dictionary:

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')
like image 20
defuz Avatar answered Sep 21 '22 21:09

defuz