3

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 ?

jith
  • 69
  • 6

1 Answers1

4

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)
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • for explanation: a tuple is returned from the lambda, and tuples are sorted 'alphabetically' (element-wise, as strings would be character-wise) – Ilja Mar 14 '16 at 08:33
  • @Ilja, `x[1]` is a value, so value is comapred first. If values of two items are equal, key(`x[0]`) is compared: `(5, 'C') > (5, 'B')` – falsetru Mar 14 '16 at 08:35
  • yes, I meant this (it was not a question but a statement :)), but wrote it more abstract – Ilja Mar 14 '16 at 08:36
  • Another way to write that key function: `lambda x: x[::-1]` – PM 2Ring Mar 14 '16 at 09:36