NEO
NEO

Reputation: 2001

sort by actual values in a dictionary python

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

Upvotes: 0

Views: 72

Answers (1)

Trein
Trein

Reputation: 3688

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')]

Upvotes: 2

Related Questions