Skip to content
Advertisement

Sort dictionary by the INT value of the value

There are many posts here about sorting dictionaries in Python so I was careful to read them and hope this is not a duplicate:

I’m using a dictionary to hold words as keys and the occurrence of the word as value. This leads to a dictionary that could be like:

JavaScript

I want to sort them by occurrence (the ‘value’)

JavaScript

I’m using the following code to try to sort my dictionary like this:

JavaScript

However this returns a sorted list of tuples that looks like this:

JavaScript

You can see the problem is that with the above code the values are sorted “alphabetically”, so 15 follows 1, even though mathematically 15 > 5 and 6 and so should be last.

How can I fix the code to treat the values as INTs and not strings

Advertisement

Answer

You have to convert to values to integers in your key expression. Use

JavaScript

It may be tempting to try something like key=int(itemgetter(1)), but this will not work since the key parameter is expecting a function.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement