1

I have a python dictionary:

dic={'a':'17','b':'9','c':'11'}

I want to find the lowest value in this dictionary and show the KEY name of that value in the example above, I want the name : b

Iron Fist
  • 10,739
  • 2
  • 18
  • 34
Ehsan Kordloo
  • 67
  • 1
  • 5
  • 7
    pleas look at this post: http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value – Eyal Ch Dec 29 '15 at 09:28

2 Answers2

5

This will do:

dic={'a':'17','b':'9','c':'11'}
min(dic.items(), key=lambda item: int(item[1]))[0]

Result:

b

This works by taking all the "items", which are the key-value pairs:

[('a', '17'), ('c', '11'), ('b', '9')]

We then use the min() function to find the one with the minimum value:

('b', '9')

The items are compared based on the int() value of the second item in each tuple by the key function:

lambda item: int(item[1])

Once we have that item ('b', '9'), we then get the key (the first item in that tuple).

Jamie Cockburn
  • 7,379
  • 1
  • 24
  • 37
  • 2
    OP wants `b`. `min(dic, key=lambda k: int(dic[k]))`. – falsetru Dec 29 '15 at 09:33
  • 1
    The values are strings. The OP wants `b` as result --> convert to `int`. – Mike Müller Dec 29 '15 at 09:35
  • Whoops, didn't type those as strings. Fixed. – Jamie Cockburn Dec 29 '15 at 09:36
  • thanks man , and what if we have 2 keys which have same value (and also lowest values in the dic) ? how can we print multiple key name if the have the lowest value in our dic ? – Ehsan Kordloo Dec 29 '15 at 09:49
  • That's rather more complicated, and probably deserves a new question. You can take the result from above, and search the dictionary manually `keys = []; for k, v in dic.items(): if v == dic[result]: keys.append(k)` – Jamie Cockburn Dec 29 '15 at 09:59
  • @EhsanKordloo: after `m = min(dic.items(), key=lambda item: int(item[1]))[1]`; you can use list comprehension `[x for x in dic.items() if x[1] == m]` or `filter((lambda x: x[1] == m), dic.items())`. – Lie Ryan Dec 29 '15 at 15:46
3
k = {'a':'17', 'b':'9', 'c':'11'}
print sorted(k, key=lambda x:int(k[x]))[0]

Output: b

or

print min(k, key=lambda x:int(k.get(x)))
The Godfather
  • 4,235
  • 4
  • 39
  • 61
vks
  • 67,027
  • 10
  • 91
  • 124