1

I have a file that contains a list of words like:

word1 34

word2 12

word3 6

word4 498

word5 50

I want to sort the file by the numerical value. My code:

sortedfreqlist = sorted(freqlist, key=operator.itemgetter(1), reverse=True)

Doesn't quite work because it sorts the numbers as words i.e 12 comes before 6 etc.

Any ideas how I can do this?

user743396
  • 13
  • 2

2 Answers2

3

The sorting is not working because your values are not of a numeric type, thus lexicographic sorting is applied. Be sure to convert your sort key to to a number, for example like this:

sortedfreqlist = sorted(freqlist, key=lambda item: int(item[1]), reverse=True)
Jim Brissom
  • 31,821
  • 4
  • 39
  • 33
  • This is the correct solution if all items in the second column can be interpreted as ints. I misunderstood the question. – Paul May 07 '11 at 20:40
0

Search "natural sort python" in your favorite search engine and you'll find many different solutions.

Here is one at activestate.

Here is a nice tidy solution at SO.

Community
  • 1
  • 1
Paul
  • 42,322
  • 15
  • 106
  • 123