bang
bang

Reputation: 181

How do I sort a dictionary?

The problem is a list of room numbers and guest details I ripped straight from a txt file that needs to be put into a dictionary with the room number as the keys and the details as the values.

The guest list is literally a list, each item represents room number, guest name, arrival, departure dates. Rooms without anything 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, got to get that into a dictionary. Here's 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 put together in no particular order. However for this particular exercise, the dictionary needs to be in order from lowest to highest room number. I guess I thought that it would just iterate through each internal list from beginning to end, test it, and just build the dictionary in that order.

Does anyone know how to write the code correctly so that the dictionary comes out as {'101': None, '102', None, '103': None... etc.)? And hopefully someone could explain why my code didn't work as I intended too.

Upvotes: 5

Views: 186

Answers (1)

NPE
NPE

Reputation: 500167

Standard Python dictionaries are inherently unordered.

One possibility is to use OrderedDict. It will preserve the insertion order, meaning that you have to insert entries in the order in which you then wish to retrieve them.

Another possibility is to keep the dict as is, but iterate in the desired order:

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

Finally, it should be noted that your example stores room numbers as strings rather than integers. This means that the ordering is lexicographic ('90' > '100'). Since this is homework, I leave it as an exercise for the reading to figure out how to fix this.

Upvotes: 10

Related Questions