Python:按升序使用键对字典进行排序

时间:2013-11-21 16:00:56

标签: python dictionary

我有以下字典,我想使用键以升序排序。

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

我尝试使用:

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

我怎么能得到:

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

2 个答案:

答案 0 :(得分:3)

对于您的具体情况,这可以起作用:

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

为什么呢?因为你的钥匙都以'anim'开头,然后有一个数字......

我使用转化为int()进行按数字排序的排序。

答案 1 :(得分:1)

您只需要根据数字部分的整数值拆分密钥和排序,就像这样

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

<强>输出

anim 0
anim 1
anim 2
anim 11
anim 21
anim 32
相关问题