Reputation: 69
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 ?
Upvotes: 3
Views: 120
Reputation: 369444
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)
Upvotes: 4