2013-07-24 239 views
-1

我创建一个图书索引,我已经在口头上和他们的网页的文本文件中读取,并创造了本词典称之为“指数”的Python排序的字典和一组

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 

和我按字母顺序排列的按键的列表,但我不知道如何接近的数字,因为他们是在套...

有什么建议?

+0

的可能重复的[Python的:按值的字典(http://stackoverflow.com/questions/613183/python-sort-a-dictionary-by-value) – Marcin

+0

@Marcin:我不我认为OP在这里按照价值排序字典。 –

回答

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 
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)