I have a dict, that looks like:
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'}
}
i want to sort it by keys(’24’,’26’,’27’, etc…), it should be like:
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'},
}
I have read articles, but i don’t understand how to sort by keys of main dict.
a
dictis a mapping, keys are not ordered. this is due to the way thedict()type is implemented: keys are hashed (using thehash()builtin function) and the order you observe derives from this hash.you will need an ordered dict for the dictionary to keep its ordering and to allow you to sort the keys. the
collections.OrderedDicttype is the builtin ordered dict for python 3.x.here is an example of sorting your data: