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'}
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'}'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With