How to sort a dictionary?

The problem is the list of room numbers and guest details, which I ripped directly from the txt file, which I need to put in the dictionary with the room number, as keys and data, as values.

The guest list is literally a list, each element represents a room number, guest name, arrival, departure date. The rooms without nothing next to them are empty.

nlist = [['101'], ['102'], ['103'], 
['201', ' John Cleese', ' 5/5/12', ' 5/7/12'], ['202'], 
['203', ' Eric Idle', ' 7/5/12', ' 8/7/12'], ['301'], ['302'], ['303']]

Basically, you need to get this in the dictionary. Here is what I tried:

guests = {}
for i in nlist:
        if len(i) == 1:
            key = i[0]
            guests[key] = None
        else:
            key = i[0]
            val = i[1],i[2],i[3]
            guests[key] = val

which gives me:

guests = {'201': (' John Cleese', ' 5/5/12', ' 5/7/12'), 
'203': (' Eric Idle', ' 7/5/12', ' 8/7/12'), '202': None, '301': None, 
'302': None, '303': None, '102': None, '103': None, '101': None}

As you can see, the dictionary is not compiled in a specific order. However, for this particular exercise, the dictionary should be in order from the lowest to the highest room number. I think I thought that he simply iterates over each internal list from beginning to end, tests it and simply builds the dictionary in that order.

- , , {'101': None, '102', None, '103': None... ..)? , , - , , .

+5
1

Python .

- OrderedDict. , , , .

, dict , :

for k, v in sorted(guests.items()):
  print k, v

, , , . , ('90' > '100'). , , , .

+10

All Articles