简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM