如何在OrderDict中更改订单?

时间:2017-06-30 10:28:10

标签: python dictionary

我有字典

from collections import OrderedDict 

md = {"r3":"piz","r1":"pic","r9":"piz","r12":"pic","r19":"lia","r2":"kurcc","r21":"jes","r99":"pic","r111":"kurcc","r116":"kurcc","r211":"ar","r221":"buc"}

print (OrderedDict(sorted(md.items(), key=lambda t: t[0])))

我想从最低的数字开始排序。但是我得到了

OrderedDict([('r1', 'pic'), ('r111', 'kurcc'), ('r116', 'kurcc'), ('r12', 'pic'), ('r19', 'lia'), ('r2', 'kurcc'), ('r21', 'jes'), ('r211', 'ar'), ('r221', 'buc'), ('r3', 'piz'), ('r9', 'piz'), ('r99', 'pic')])

如何更改代码以使r1,r2,r3顺序?

1 个答案:

答案 0 :(得分:5)

如果所有密钥的格式为'r???'???为整数,我们可以使用以下排序键:

OrderedDict(sorted(md.items(), key=lambda t: int(t[0][1:])))

所以在这里我们首先使用t[0]来获取密钥,就像你自己做的那样。接下来,我们获取从索引1开始的子字符串(因此我们删除'r'),最后我们将其转换为int(..)以执行数值比较。

这会产生:

>>> OrderedDict(sorted(md.items(), key=lambda t: int(t[0][1:])))
OrderedDict([('r1', 'pic'), ('r2', 'kurcc'), ('r3', 'piz'), ('r9', 'piz'), ('r12', 'pic'), ('r19', 'lia'), ('r21', 'jes'), ('r99', 'pic'), ('r111', 'kurcc'), ('r116', 'kurcc'), ('r211', 'ar'), ('r221', 'buc')])