0

Dictionary:

d = {u'A': 240, u'B': 242, u'C': 243}

I have successfully managed to identify the lowest key using the following code:

min_ = min(d, key=d.get)

Output:

A

I'd like to make the output contain the value as well:

A, 240


Note:

I'd like to avoid the use of lambda if possible

Enigmatic
  • 3,902
  • 6
  • 26
  • 48

1 Answers1

4

Apply min to the dictionary items then:

from operator import itemgetter

min(d.items(), key=itemgetter(1))

I used the operator.itemgetter() callable to retrieve the value from each (key, value) pair, but you could also use lambda pair: pair[1]. The latter will be slightly slower as it involves dropping back into a Python call frame.

Demo:

>>> from operator import itemgetter
>>> d = {u'A': 240, u'B': 242, u'C': 243}
>>> min(d.items(), key=itemgetter(1))
(u'A', 240)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Awesome, Thanks for this! Is there a simple way to remove the "Unnecessary Characters" i.e. "( u ' )", so I'm left with `A, 240`? – Enigmatic Apr 22 '17 at 14:42
  • @LearningToPython: you are echoing or printing a *tuple*, so `repr()` is used; tuples are not meant to end-user friendly, they only have a debugging-friendly representation. If you want to format that to something else, use string formatting. `'{}, {}'.format(*result)` would format it the way you want it (put the two values into a string with a comma and a space). – Martijn Pieters Apr 22 '17 at 14:44
  • Thanks - I found I could doing `x[0]` and `x[1]` gave me the result – Enigmatic Apr 22 '17 at 15:02