Python's sorted function to sort the dictionary by key and sort by value

Source: Internet
Author: User
Tags comparison iterable

1.sorted functions sort the dictionary by key value

First of all, the basic introduction of the sorted function, sorted (iterable,key,reverse), sorted have iterable,key,reverse these three parameters.

Where iterable represents an object that can be iterated, such as Dict.items (), Dict.keys (), and so on, the key is a function that selects the elements that participate in the comparison, and reverse is used to specify whether the sort is reversed or sequential, reverse= True is reverse, reverse=false is the order, default is Reverse=false.

To sort the dictionary by key value, you can use the following statement:

Directly using sorted (D.keys ()) You can sort the dictionary by key value, where you sort the key values in order, and if you want to sort by reverse, just place the reverse as true.

2.sorted function to sort dictionaries by value value

To sort the value of a dictionary, you need a key parameter, which provides a way to use a lambda expression, as follows:

The D.items () here is actually converting D to an iterative object, the elements of the Iteration object are (' Lilee ', 25), (' Wangyan ', 21), (' Liqun ', 32), (' lidaming ', '), the items () method converts the elements of the dictionary Converted to tuples, and here the key parameter's lambda expression means to select the second element in the tuple as the comparison parameter (if writing KEY=LAMBDA item:item[0] then select the first element as the comparison object, the key value as the comparison object. In Lambda X:y, x represents the output parameter, and Y represents the return value of the lambda function, so this method can be used to sort the value of the dictionary. Note that the sorted return value is a list, and the name value pairs in the original dictionary are converted to tuples in the list.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.