2013-11-21 123 views
1

我有以下字典,我想用按键升序排列。Python:通过使用键升序对字典进行排序

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 

回答

3

针对您的特殊情况下,这可以工作:

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

为什么?因为你的密钥全部以'anim'开头,然后有一个数字...

我使用了一个转换为int()进行按数字排序的行为。

+1

注意,这有什么用它做作为一个字典,并且只处理'str(10) int(2)'的事实。 – colcarroll

+0

上面的代码正在工作。真棒谢谢:) – user3018319

+0

@JLLagrange,好点。有时指出明显应该是第一件事!谢谢。 –

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 
相关问题