user743396
user743396

Reputation: 13

Python sorting a file by frequency

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?

Upvotes: 1

Views: 248

Answers (2)

Jim Brissom
Jim Brissom

Reputation: 32929

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)

Upvotes: 3

Paul
Paul

Reputation: 43620

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.

Upvotes: 0

Related Questions