Python dict sorting

Source: Internet
Author: User

Python dict is unordered and extracts the corresponding value according to the key. If we need to sort the value, Python dict can be sorted by the following method:

The following is the order of values from large to small.

Dic = {'A': 31, 'bc': 5, 'C': 3, 'asd ': 4, 'A': 74, 'D': 0}
Dict = sorted (DIC. iteritems (), Key = Lambda D: d [1], reverse = true)
Print dict

Output result:
[('A', 74), ('A', 31), ('bc', 5), ('asd ', 4), ('C ', 3), ('D', 0)]

Next let's break it downCode
Print DIC. iteritems () to obtain the [(Key, value)] list.
Then, use the sorted method and the key parameter to specify that the sorting is based on the value, that is, the value of the first element d [1. Reverse = true indicates that the system needs to be flipped. The default value is from small to large. If it is flipped, it is from large to small.

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.