0

I am having trouble in sorting dictionary. I am using the below code to sort them

sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1)) 

but the problem is the sort is not done by actual values..

asdl 1
testin 42345
alpha 49

Ref: Sorting a dictionary in python

I need the items sorted like below

asdl 1
alpha 49
testin 42345
Community
  • 1
  • 1
NEO
  • 1,961
  • 8
  • 34
  • 53

1 Answers1

2

The behavior the you are experiencing is due to the type of the compared variable. In order to solve it, cast it to Integer.

orted(x.iteritems(), key=lambda x: int(x[1]))

The final result will be:

[('asdl', '1'), ('alpha', '49'), ('testin', '42345')]
Trein
  • 3,658
  • 27
  • 36
  • Yes, this works. But when I update the dict am doing by x.update({line.split()[0]:line.split()[1]}). By default it will take it as string? – NEO Apr 22 '14 at 03:49
  • Yes, it will. Since you are splitting a `String`, the result will be a `String`. But you can cast it to `Integer` by calling `int()` if you are sure the returned value will always be an `Integer`. – Trein Apr 22 '14 at 03:52