Filip Minx
Filip Minx

Reputation: 2488

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?

Upvotes: 5

Views: 166

Answers (3)

poke
poke

Reputation: 387607

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'

Upvotes: 8

Nafiul Islam
Nafiul Islam

Reputation: 82470

>>> max(d, key = lambda x: d[x]['c'] + d[x]['h'])
'b'
>>> d
{'a': {'h': 2, 'c': 1}, 'c': {'h': 1, 'c': 2}, 'b': {'h': 5, 'c': 3}, 'd': {'h': 1, 'c': 4}}

Upvotes: 7

mdml
mdml

Reputation: 22882

You can use max to find the key of the item with the highest sum in a dictionary of dictionaries. Just pass max a suitable key function:

>>> d = {
...     'a' : {'c' : 1, 'h' : 2},
...     'b' : {'c' : 3, 'h' : 5},
...     'c' : {'c' : 2, 'h' : 1},
...     'd' : {'c' : 4, 'h' : 1}
... }
>>> max( d, key=lambda k: d[k]['c'] + d[k]['h'] )
'b'

Upvotes: 6

Related Questions