We often encounter the problem of word frequency sorting in computer level exams, we usually first count the frequency of words by generating a dictionary, and then sort the dictionary. So how to quickly sort the dictionary by key value? Three methods are described below. The first method is relatively common, but the second method you may have seen for the first time, and the third method is one of the more troublesome ones.
Example: have the following list dic={'a':.4, 'b': 3, 'c': 2, 'd': 1}, how can we achieve ascending ordering of dictionaries?
The first: using the custom function lambda
>>> dic={'a': 4, 'b': 3, 'c': 2, 'd': 1} >>> sorted((), key=lambda x: x[1]) [('d', 1), ('c', 2), ('b', 3), ('a', 4)]
Here, through () to get a list of tuples consisting of dictionary key names and key values, and then through a custom function, get the second element of the tuple, as the basis for sorting that is key, the default is in ascending order, if it is in descending order you can set reverse to True, that is:
>>> dic={'a': 4, 'b': 3, 'c': 2, 'd': 1} >>> sorted((), key=lambda x: x[1],reverse=True) {'a': 4, 'b': 3, 'c': 2, 'd': 1}
The second: utilizing the operator's method
>>> import operator >>> sorted((), key=(1)) [('d', 1), ('c', 2), ('b', 3), ('a', 4)]
operator. itemgetter(item)
operator. itemgetter(*items)
The function is to return a callable object that can capture items from its own operations using the operation __getitem__() method. if more than one items are formulated, a tuple of the query value is returned. For example, running f =itemgetter(2) and then calling f(r) returns r[2]. Here the key value in () is obtained via operator. Note that operator is a built-in package and does not need to be installed.
The third method: List Derivative Method
>>> dic={'a': 4, 'b': 3, 'c': 2, 'd': 1} >>> tup=[(x[1],x[0]) for x in ()]# elements swap places >>> sorted(tup) # Sort [(1, 'd'), (2, 'c'), (3, 'b'), (4, 'a')] >>> [(x[1],x[0]) for x in ()] >>> [(x[1],x[0]) for x in tup] # Switch back to the original position >>> [('d', 1), ('c', 2), ('b', 3), ('a', 4)]
Using list derivatives, swapping the positions of elements in a tuple, sorting them and then swapping them back is a bit of a pain in the ass, but the logic is clear and suitable for newbies. What other good methods, welcome to put forward, together to exchange.
Fourth method: using Counter's method
from collections import Counter dic={'a': 4, 'b': 3, 'c': 2, 'd': 1} count = Counter(dic) print(list(()))
Summary: The above four methods are common sorting methods for your reference and study.
to this article on the Python dictionary sorting of the four methods of the article is introduced to this, more related Python dictionary sorting content, please search for my previous posts or continue to browse the following related articles I hope you will support me in the future more!