Nishant bakshi
Nishant bakshi

Reputation: 11

Sorting a dictionary based on values

I searched for sorting a Python dictionary based on value and got various answers on the internet.Tried few of them and finally used Sorted function. I have simplified the example to make it clear. I have a dictionary,say:

temp_dict = {'1': '40', '0': '109', '3': '37', '2': '42', '5': '26', '4': '45', '7': '109', '6': '42'}

Now ,to sort it out based on value,I did the following operation(using Operator module):

sorted_temp_dict = sorted(temp_dict.items(), key=operator.itemgetter(1))

The result I'm getting is(The result is a tuple,which is fine for me):

[('0', '109'), ('7', '109'), ('5', '26'), ('3', '37'), ('1', '40'), ('2', '42'), ('6', '42'), ('4', '45')]

The issue is,as you can see,the first two elements of the tuple is not sorted.The rest of the elements are sorted perfectly based on the value. Not able to find the mistake here.Any help will be great.Thanks

Upvotes: 1

Views: 156

Answers (3)

bcap
bcap

Reputation: 500

The problem is trying to sort with values that are str, and not int. If you first convert the values into int and then sort, it will work.

Upvotes: 1

Anand S Kumar
Anand S Kumar

Reputation: 90889

They are sorted, the issue is that the elements are string , hence -

'109' < '26'  # this is true, as they are string

Try converting them to int for the key argument, you can use a lambda such as -

>>> sorted_temp_dict = sorted(temp_dict.items(), key=lambda x: int(x[1]))
>>> sorted_temp_dict
[('5', '26'), ('3', '37'), ('1', '40'), ('6', '42'), ('2', '42'), ('4', '45'), ('7', '109'), ('0', '109')]

Upvotes: 3

Daniel Roseman
Daniel Roseman

Reputation: 599490

Those are sorted. They are strings, and are sorted lexicographically: '1' is before '2', etc.

If you want to sort by numeric value, you'll need to convert to ints in the key function. For example:

sorted(temp_dict.items(), key=lambda x: int(x[1]))

Upvotes: 3

Related Questions