我有一个名为data的python字典,里面有子字典,比如
data = {'ind1' : {}, 'ind10' : {}, 'ind11' : {}, 'ind12' : {}, 'ind13', 'ind14' : {}, 'ind15' : {}, 'ind16' : {}, 'ind17' : {}, 'ind18' : {}, 'ind19' : {}, 'ind2' : {}, 'ind20' : {}, 'ind3' : {}, 'ind30' : : {}, 'ind31' : {} 'ind5' : {}, 'ind6' : {}, 'ind7' : {}, 'ind8' : {}, 'ind9' : {}}
我想把字典里的数据按键排序为
^{pr2}$我尝试从集合库中data = collections.OrderedDict(sorted(data.items()))
这就是结果
ind1 : {}
ind11 : {}
ind12 : {}
ind13 : {}
.....
ind20 : {}
ind21 : {}
....
ind3 : {}
ind4 : {}
....
请帮忙
您真的想在字典中对数据进行排序,还是只想对.keys()提供的列表进行排序?在
如果只对值列表排序,则此链接应包含所需内容:https://wiki.python.org/moin/HowTo/Sorting
如果你想在字典里整理数据,我很想知道为什么。我会跟进并在您回复时添加建议。在
祝你好运!在
你需要在密钥前面加上“ind”前缀吗?你可以使用整数作为键来正确排序。现在它是按字母顺序排序的,这就是问题的起因。在
如果不能,假设您的密钥遵循相同的格式,请使用以下命令进行排序:
它使用前缀后面的整数进行排序。在
如果希望“ind10”位于“ind9”之后,则需要对键使用自然排序算法;^)
来自于ActiveState的wizkid
相关问题 更多 >
编程相关推荐