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

  • A+
Category:Languages

This question already has an answer here:

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?


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'} 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: