Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get keys with maximum value from a nested dictionary

Thanks in advance for your help.

I built the following code (I tried the below, I used a dictionary within a dictionary).

import operator
character = {'eyes_color':{"blue":10,"brown":12},
         'hair_color':{"black":15, "blonde":7},
         'gender': {"male":16,"female":6}
         }
maximun_key=max(character.items(), key=operator.itemgetter(1))[0]

As you can see, I used in my code:

maximun_key=max(character.items(), key=operator.itemgetter(1))[0]

Getting as output:

brown

male

black

i.e. the maximum, but for each dictionary.

I expected for this case an output like:

male

I mean the keys with maximum values.

Does anyone know how I can solve this problem?

like image 524
Lorenzo Castagno Avatar asked Mar 13 '26 02:03

Lorenzo Castagno


1 Answers

In simple way with builtin features:

d = {'eyes_color': {"blue": 10, "brown": 12},
     'hair_color': {"black": 15, "blonde": 7},
     'gender': {"male": 16, "female": 6}
     }

max_value, max_key = max(((v,k) for inner_d in d.values() for k,v in inner_d.items()))
print(max_key)   # male
print(max_value) # 16
like image 96
RomanPerekhrest Avatar answered Mar 15 '26 16:03

RomanPerekhrest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!