-3

I'm relatively new to Python (2.7 import future) so please forgive me if this is a stupid question.

I've got a dictionary of values[key]. I'm trying to get the second highest value from the list, but write readable code. I could do it by mapping to sortable types, but it's confusing as hell, and then I would have to juggle the key. Any suggestions for how to do it cleanly would be much appreciated.

cjm2671
  • 18,348
  • 31
  • 102
  • 161

3 Answers3

1

2nd highest value in a dictionary:

from operator import itemgetter
# Note that this now returns a k, v pair, not just the value.
sorted(mydict.items(), key = itemgetter(1))[1]

Or more specifically, the 2nd value in the sorted representation of values. You may need to reverse sort order to get the value you actually want.

g.d.d.c
  • 46,865
  • 9
  • 101
  • 111
  • 1
    `sorted(mydict.values(), reverse=True)[1]` ? – candu Apr 28 '14 at 19:18
  • How do I retrieve the key for that value? – cjm2671 Apr 28 '14 at 19:27
  • 1
    @cjm2671 - I've updated my answer to include retrieving the key as well. While the shorthand is convenient, note from the other question you were linked to that this is `O(N log N)`, while an `O(N)` solution is possible. – g.d.d.c Apr 28 '14 at 19:30
0

If you also want the key associated with that value, I would do something like:

# Initialize dict
In [1]: from random import shuffle
In [2]: keys = list('abcde')
In [3]: shuffle(keys)
In [4]: d = dict(zip(keys, range(1, 6)))
In [5]: d
Out[5]: {'a': 4, 'b': 1, 'c': 5, 'd': 3, 'e': 2}
# Retrieve second highest value with key
In [6]: sorted_pairs = sorted(d.iteritems(), key=lambda p: p[1], reverse=True)
In [7]: sorted_pairs
Out[7]: [('c', 5), ('a', 4), ('d', 3), ('e', 2), ('b', 1)]
In [8]: sorted_pairs[1]
Out[8]: ('a', 4)

The key=lambda p: p[1] tells sorted to sort the (key, value) pairs by the value, and reverse tells sorted to place the largest values first in the resulting list.

wflynny
  • 18,065
  • 5
  • 46
  • 67
0

This should do the trick:

maximum, max_key = None, None
second, second_key = None, None
for key, value in dictionary.iteritems():
  if maximum < value:
     second = maximum
     second_key = max_key
     maximum = value
     maxi_key = second_key
radu.ciorba
  • 1,024
  • 1
  • 8
  • 14