Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find key of object with maximum property value

I have dictionary of dictionaries like this.

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

I need to get key of the item that has highest value of c + h.

I know you can get key of item with highest value in case like this:

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

Is it possible to use the max function in my case?

like image 431
Filip Minx Avatar asked Nov 29 '13 18:11

Filip Minx


1 Answers

You can specify your own function for key which can do fancy stuff like getting the value for both c and h and add those up. For example using an inline-lambda:

>>> max(d, key=lambda x: d[x]['c'] + d[x]['h'])
'b'
like image 192
poke Avatar answered Sep 29 '22 15:09

poke