本文共 8119 字,大约阅读时间需要 27 分钟。
Note: If you want to sort a list, tuple or object in Python, checkout this article:
The dict
(dictionary) class object in Python is a very versatile and useful container type, able to store a collection of values and retrieve them via keys. The values can be objects of any type (dictionaries can even be nested with other dictionaries) and the keys can be any object so long as it's hashable, meaning basically that it is immutable (so strings are not the only valid keys, but mutable objects like lists can never be used as keys). Unlike Python lists or tuples, the key and value pairs in dict
objects are not in any particular order, which means we can have a dict
like this:
Although the key-value pairs are in a certain order in the instantiation statement, by calling the list
method on it (which will create a list from its keys) we can easily see they aren't stored in that order:
If we want to order or sort the dictionary objects by their keys, the simplest way to do so is by Python's built-in sorted
method, which will take any iterable and return a list of the values which has been sorted (in ascending order by default). There is no class method for sorting dictionaries as there is for lists, however the sorted
method works the same exact way. Here's what it does with our dictionary:
We can see this method has given us a list of the keys in ascending order, and in almost alphabetical order, depending on what we define as "alphabetical." Also notice that we sorted its list of keys by its keys — if we want to sort its list of values by its keys, or its list of keys by its values, we'd have to change the way we use the sorted
method. We'll look at these different aspects of sorted
in a bit.
In the same way as we did with the keys, we can use sorted
to sort the Python dictionary by its values:
This is the list of values in the default order, in ascending order. These are very simple examples so let's now examine some slightly more complex situations where we are sorting our dict
object.
If we simply give the sorted
method the dictionary's keys/values as an argument it will perform a simple sort, but by utilizing its other arguments (i.e. key
and reverse
) we can get it to perform more complex sorts.
The key
argument (not to be confused with the dictionary's keys) for sorted
allows us to define specific functions to use when sorting the items, as an iterator (in our dict
object). In both examples above the keys and values were both the items to sort and the items used for comparison, but if we want to sort our dict
keys using our dict
values, then we would tell sorted
to do that via its key
argument. Such as follows:
With this statement we told sorted
to sort the numbers dict
(its keys), and to sort them by using numbers' class method for retrieving values — essentially we told it "for every key in numbers, use the corresponding value in numbers for comparison to sort it.".
We can also sort the values in numbers by its keys, but using the key
argument would be more complicated (there is no dictionary method to return a key by using a certain value, as with the list.index
method). Instead we can use a to keep it simple:
Now the other argument to consider is the reverse
argument. If this is True
, the order will be reversed (descending), otherwise if it's False
it will be in the default (ascending) order, it's as simple as that. For example, as with the two previous sorts:
These sorts are still fairly simple, but let's look at some special algorithms we might use with strings or numbers to sort our dictionary.
Sorting strings in alphabetical order is very common, however using sorted
might not sort the keys/values of our dict
in the "proper" alphabetical order, i.e. ignoring the case. To ignore the case we can again utilize the key
argument and the str.lower
(or str.upper
) method so that all strings are the same case when comparing them:
For associating strings with numbers, we need an extra element of context to associate them properly. Let's make a new dict
object first:
This contains only string keys and values, so there'd be no way to put the months in the correct order without additional context. To do so we can simply create another dictionary to map the strings to their numerical values and use that dictionary's __getitem__
method to compare the values in our month
dictionary:
As we can see, it still returned a sorted list of its first argument (month). To return the months in order, we'll use a again:
If we wanted to sort our key/value strings by the number of repeated letters in each string, we could define our own custom method to use in the sorted
key argument:
Using the function can be performed as follows:
Now let's say we have a dictionary keeping track of the number of students in a class for each of these months, like so:
If we want to organize the class sizes with the even numbers first and odd numbers second, we could do so with a definition like this:
Using the evens1st
sorting function, gives us the following output:
Likewise we could list the odd class sizes first, and perform many other algorithms to get our sort exactly how we want. There are many other intricate sorting methods and tricks you could use with dictionaries (or any iterable object), but for now hopefully these examples have provided a good starting point.
转载地址:http://pohbi.baihongyu.com/