2

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

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'}
}

我想按键('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'}, 
}

我读过文章,但我不明白如何按主字典的键排序。

4

7 回答 7

6

字典没有排序/排序。如果您使用的是 python 2.7,则可以使用 OrderedDict。

于 2011-08-30T07:26:54.113 回答
5

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

for channelName, channelValue in sorted(channels.items()):
    ...
于 2011-08-30T07:28:12.303 回答
2

adict是一个映射,键是无序的。这是由于dict()类型的实现方式:键被散列(使用hash()内置函数),并且您观察到的顺序来自此散列。

您将需要字典的有序字典以保持其顺序并允许您对键进行排序。collections.OrderedDict类型是 python 3.x 的内置有序字典。

这是对数据进行排序的示例:

import collections

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'}
}

channels = collection.OrderedDict(sorted(channels.items(), key=lambda item: item[0]))
for key,value in channels.items():
    print(key, ':', value)
于 2011-08-30T07:26:51.520 回答
1

dict 未排序。但是,如果您想以所描述的方式进行迭代,则可以按如下方式进行:

for key in sorted(channels):
    print key

结果是:

20
21
22
23
24
26
27

或者使用 collections.OrderedDict。

于 2011-08-30T07:28:59.417 回答
0

dict 没有按顺序排列的键,因此无法保证顺序。如果您想创建一个字典列表,您将丢失关键信息。

如果您需要排序迭代,您可以使用

for key in sorted(dict):
    ....
于 2011-08-30T07:28:30.680 回答
0
result=collections.OrderedDict(sorted(your_dict.items()))
于 2011-08-30T07:29:54.407 回答
0

尝试类似的东西:

print [ {i: channels[i] } for  i in sorted(channels)]
于 2011-08-30T07:39:19.227 回答