官术网_书友最值得收藏!

Sorting dictionaries

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

Note that the first line in the preceding code sorts the keys according to alphabetical order, and the second line sorts the values in order of 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 to use 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, for example:

Now, let's say we are given the following dictionary, English words as keys and French words as values. Our task is to place these string values in 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:

主站蜘蛛池模板: 上虞市| 海伦市| 涞水县| 叶城县| 罗田县| 双峰县| 凌云县| 延津县| 哈尔滨市| 广水市| 顺平县| 中江县| 邹城市| 奉化市| 眉山市| 曲阜市| 景宁| 南丹县| 阿拉善左旗| 蒙城县| 民勤县| 洪湖市| 翁牛特旗| 海原县| 进贤县| 赣州市| 泽普县| 灵石县| 昌图县| 汉源县| 宁波市| 绥阳县| 阿合奇县| 和林格尔县| 虞城县| 新田县| 沙湾县| 元江| 大同县| 都兰县| 永修县|