如何按键排序词典?

alt*_*pub 2 python sorting dictionary key sorted

我有一个字典,看起来像:

channels = {
'24': {'type': 'plain', 'table_name': 'channel.items.AuctionChannel'}, 
'26': {'type': 'plain', 'table_name': 'channel.gm.DeleteAvatarChannel'}, 
'27': {'type': 'plain', 'table_name': 'channel.gm.AvatarMoneyChannel'}, 
'20': {'type': 'plain', 'table_name': 'channel.gm.AvatarMoneyAssertChannel'}, 
'21': {'type': 'plain', 'table_name': 'channel.gm.AvatarKillMobComplexChannel'}, 
'22': {'type': 'plain', 'table_name': 'channel.gm.DistributionMarkChannel'}, 
'23': {'type': 'plain', 'table_name': 'channel.gm.MailChannel'}
}
Run Code Online (Sandbox Code Playgroud)

我想用键('24','26','27'等等)对它进行排序,它应该是这样的:

channels = {
'20': {'type': 'plain', 'table_name': 'channel.gm.AvatarMoneyAssertChannel'}, 
'21': {'type': 'merged', 'table_name': 'channel.gm.AvatarKillMobComplexChannel'}, 
'22': {'type': 'plain', 'table_name': 'channel.gm.DistributionMarkChannel'}, 
'23': {'type': 'plain', 'table_name': 'channel.gm.MailChannel'}
'24': {'type': 'merged', 'table_name': 'channel.items.AuctionChannel'}, 
'26': {'type': 'plain', 'table_name': 'channel.gm.DeleteAvatarChannel'}, 
'27': {'type': 'plain', 'table_name': 'channel.gm.AvatarMoneyChannel'}, 
}
Run Code Online (Sandbox Code Playgroud)

我读过文章,但我不明白如何按主要词典的键排序.

Thi*_*ter 6

Dicts没有排序/订购.如果您使用的是python 2.7,则可以使用OrderedDict.


eum*_*iro 5

标准dict未排序.但是,您可以按排序顺序迭代其键和值:

for channelName, channelValue in sorted(channels.items()):
    ...
Run Code Online (Sandbox Code Playgroud)