简体   繁体   中英

Maximum key value from dictionary

I have a python dictionary with values

d = {'A': 0, 'B': 1, 'C': 0, 'D': 4}

result = max(d.iteritems(), key=lambda x: x[1])

result = ('D', 4)

Now if there is no maximum value and all values are equal, then result should be by alphabetical order (ascending) of keys.

ie

 d = {'A': 0, 'B': 1, 'C': 0, 'D': 1}
 result should be  D

 d = {'A': 0, 'B': 5, 'C': 5, 'D': 1}
 result should be C

How this can be done in Python ?

Adjust the lambda to check the key after the value (by returning a value-key pair)

>>> d = {'A': 0, 'B': 1, 'C': 0, 'D': 1}
>>> max(d.iteritems(), key=lambda x: (x[1], x[0]))
('D', 1)
>>> d = {'A': 0, 'B': 5, 'C': 5, 'D': 1}
>>> max(d.iteritems(), key=lambda x: (x[1], x[0]))
('C', 5)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM