Python在字典和集合中排序

时间:2013-07-24 21:31:02

标签: python python-3.x

我正在创建一个图书索引,我已经在文字文件中读取了单词及其页面,并创建了这个名为'index'的字典

index={'spanning tree': {16, 99}, 'vertex': {54}, 'depth first search': {55}, 'shortest path': {55}, 'connected': {28, 54}, 'neighbor': {64, 27, 77}, 'path': {72, 19}}

现在我想按字母顺序排列并按时间顺序排列数字 - 我能够以字典格式执行此操作,还是需要将其转换为列表或字符串?

我试过这样做......

ind=list(index)
ind.sort()
return ind

我按字母顺序得到了一个按键列表,但我不确定如何处理这些数字,因为它们已经存在...

有什么建议吗?

2 个答案:

答案 0 :(得分:2)

如果您想要应用订购,您还必须将集转换为列表。

sorted() function为您提供了任何可迭代的排序列表,让您跳过一步:

for key in sorted(index):
    print('{:<20}{}'.format(key, ', '.join(str(i) for i in sorted(index[key]))))

简短演示:

>>> sorted(index)
['connected', 'depth first search', 'neighbor', 'path', 'shortest path', 'spanning tree', 'vertex']
>>> sorted(index['connected'])
[28, 54]
>>> for key in sorted(index):
...     print('{:<20}{}'.format(key, ', '.join(str(i) for i in sorted(index[key]))))
... 
connected           28, 54
depth first search  55
neighbor            27, 64, 77
path                19, 72
shortest path       55
spanning tree       16, 99
vertex              54

答案 1 :(得分:0)

您可以使用标准库中的集合模块,该模块具有OrderedDict类型,只有dict可以记住插入顺序。

如果您想按字母顺序排列字典,那么您的值是有序列表:

sorted_index = collections.OrderedDict(sorted(zip(index, map(sorted, index.values()))))

由于这有点丑陋,你可以把它扩展为。

sorted_items = sorted(index.items())
sorted_items = [(k, sorted(v)) for k, v in sorted_items]
sorted_index = collections.OrderedDict(sorted_items)