Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 722
bang Avatar asked May 16 '12 16:05

bang


People also ask

How do you sort a dictionary by sorted?

Sort Dictionary Using the sorted() Function When sorting a dictionary, we can pass one more argument to the sorted() function like this: sorted(dict1, key=dict1. get) . Here, key is a function that's called on each element before the values are compared for sorting.

Can we sort dictionary values?

It is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, such as lists and tuples, are not. So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples.

Which function is used to sort the dictionary?

Like lists, we can use the sorted() function to sort the dictionary by keys.


1 Answers

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.

like image 84
NPE Avatar answered Oct 03 '22 11:10

NPE