Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to identify highest value key in nested dictionary? [duplicate]

Tags:

python

As a python newbie, I have a dictionary d:

d={'a':{'1':4,'2':6},'b':{'1':5,'2':10}}

I need to find for each key ('a','b') the sub-key for the highest value and bundle them together in a new dictionary, newd, which looks like

newd={'a':'2', 'b':'2'}

what is the best way to achieve this?

like image 672
CWeeks Avatar asked May 04 '18 21:05

CWeeks


Video Answer


2 Answers

You can use a dictionary comprehension with max:

d={'a':{'1':4,'2':6},'b':{'1':5,'2':10}}
new_d = {a:max(b, key=b.get) for a, b in d.items()}

Output:

{'a': '2', 'b': '2'}
like image 176
Ajax1234 Avatar answered Oct 05 '22 23:10

Ajax1234


d = {'a': {'1':4,'2':6},'b': {'1':5,'2':10}}

newd = {}
for key, value in d.items():
    max_value = max([i for i in value.values()])
    for k in value:
            if value[k] == max_value:
                    newd[key] = k

print(newd)
# prints '{'a': '2', 'b': '2'}'
like image 33
Daniele Cappuccio Avatar answered Oct 05 '22 23:10

Daniele Cappuccio