5

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?

CWeeks
  • 407
  • 1
  • 5
  • 15
  • What should this do if two keys have the highest value, like `{'a': {'1': 4, '2': 4}}`? Pick one arbitrarily? – abarnert May 04 '18 at 21:27

3 Answers3

10

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'}
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
2
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'}'
Daniele Cappuccio
  • 1,952
  • 2
  • 16
  • 31
1
new_dict = {}
for k, v in d.items():
    new_dict[k] = max(v.values())
suri
  • 171
  • 1
  • 1
  • 6