Sorting dictionaries

If we want to do a simple sort on either the keys or values of a dictionary, we can do the following:

>>> d = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6} 
>>> sorted(list(d))
['five', 'four', 'one', 'six', 'three', 'two']
>>> sorted(list(d.values()))
[1, 2, 3, 4, 5, 6]

Note that the first line in the preceding code sorts the keys alphabetically and the second line sorts the values in order of the integer value.

The sorted() method has two optional arguments that are of interest: key and reverse. The key argument has nothing to do with the dictionary keys, but rather is a way of passing a function to the sort algorithm to determine the sort order. For example, in the following code, we use the __getitem__ special method to sort the dictionary keys according to the dictionary values:

Essentially, what the preceding code is doing is, for every key in d, it uses the corresponding value to sort. We can also sort the values according to the sorted order of the dictionary keys. However, since dictionaries do not have a method to return a key by using its value, the equivalent of the list.index method for lists, using the optional key argument to do this is a little tricky. An alternative approach is to use a list comprehension, as the following example demonstrates:

The sorted() method also has an optional reverse argument, and unsurprisingly this does exactly what it says—reverses the order of the sorted list, as in the following example:

Now, let's say we are given the following dictionary, with English words as keys and French words as values. Our task is to place the string values in the correct numerical order:

d2={'one':'uno','two':'deux','three':'trois','four':'quatre','five':'cinq','six':'six'}

Of course, when we print this dictionary out, it will be unlikely to print in the correct order. Because all keys and values are strings, we have no context for numerical ordering. To place these items in correct order, we need to use the first dictionary we created, mapping words to numerals as a way to order our English to French dictionary:

Notice we are using the values of the first dictionary, d, to sort the keys of the second dictionary, d2. Since our keys in both dictionaries are the same, we can use a list comprehension to sort the values of the French to English dictionary:

We can, of course, define our own custom method that we can use as the key argument to the sorted method. For example, here we define a function that simply returns the last letter of a string:

def corder(string): 
return (string[len(string)-1])

We can then use this as the key to our sorted function to sort each element by its last letter:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset