Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 774
jith Avatar asked May 31 '26 06:05

jith


1 Answers

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)
like image 171
falsetru Avatar answered Jun 01 '26 20:06

falsetru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!