user3018319
user3018319

Reputation: 11

Python : Sort a dictionary by using keys in ascending order

I have the following dictionary and I want to order it in ascending using the keys.

animMeshes = { "anim 0" : 23, "anim 32": 4, "anim 21" : 5, "anim 2" : 66, "anim 11" : 7 , "anim 1" : 5}

I tried using :

for mesh,val in sorted(animMeshes.items(), key=lambda t: t[0]):
    print mesh

o/p :

anim 0
anim 1
anim 11
anim 2
anim 21
anim 32

How could I get :

anim 0
anim 1
anim 2
anim 11
anim 21
anim 32

Upvotes: 1

Views: 877

Answers (2)

thefourtheye
thefourtheye

Reputation: 239683

You just have to split the key and sort based on the integer value of the number part, like this

for mesh, val in sorted(animMeshes.items(), key=lambda t: int(t[0].split()[1])):
    print mesh

Output

anim 0
anim 1
anim 2
anim 11
anim 21
anim 32

Upvotes: 1

Daren Thomas
Daren Thomas

Reputation: 70354

For your specific case, this can work:

for mesh,val in sorted(animMeshes.items(), key=lambda t: int(t[0].split()[1])):
    print mesh

Why? because your keys all start with 'anim' and then have a number...

I used a conversion to int() for the sorting by number behaviour.

Upvotes: 3

Related Questions