-1

I'm creating a book index and I have read in a text file of words and their pages and have created this dictionary called '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}}

Now I want to alphabetize the keys and put the numbers in chronological order- Am I able to do this in the dictionary format or do I need to convert it to a list or a string?

I tried doing this...

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

and I got a list of the keys in alphabetical order but am not sure how to approach the numbers because they are in sets...

Any advice?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
user2553807
  • 329
  • 5
  • 10
  • 22

2 Answers2

2

You'll have to convert the sets to lists too if you want to apply ordering.

The sorted() function gives you a sorted list from any iterable, letting you skip a step:

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

Short demo:

>>> 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
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

You can use the collections module in the standard library which has an OrderedDict type which is just a dict that remembers order of insertion.

If you want a dictionary in alphabetical order, where your values are ordered lists:

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

Since that is a bit of an ugly line you can expand it out as.

sorted_items = sorted(index.items())
sorted_items = [(k, sorted(v)) for k, v in sorted_items]
sorted_index = collections.OrderedDict(sorted_items)
RussW
  • 427
  • 4
  • 11