Python dictionary (dict) key and value sorting

Source: Internet
Author: User
The following small series will bring you a python dictionary (dict) key and value sorting. I think this is quite good. now I will share it with you and give you a reference. Let's take a look at the following small series to bring you a python dictionary (dict) key and value sorting. I think this is quite good. now I will share it with you and give you a reference. Let's take a look at it with Xiaobian.

The characteristics of the python dictionary (dict) are unordered. the corresponding values are extracted by key. if we need to sort the dictionary by value, you can use the following method:

1. values are sorted in the ascending order of values.

Dic = {'a': 31, 'BC': 5, 'C': 3, 'asd ': 4, 'A': 74, 'D ': 0} dict = sorted (dic. items (), key = lambda d: d [1], reverse = True) print (dict)

Output result:

[('A', 74), ('A', 31), ('BC', 5), ('asd ', 4), ('C ', 3), ('D', 0)]

The following code is broken down:

Print dic. items () 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.

2 pairs of dictionary key sorting:

Dic = {'a': 31, 'BC': 5, 'C': 3, 'asd ': 4, 'A': 74, 'D ': 0} dict = sorted (dic. items (), key = lambda d: d [0]) print dict

The above is all the python dictionary (dict) keys and values sorted by the editor. I hope you can support PHP ~

For more python dictionary (dict) key-value sorting articles, refer to PHP Chinese network!

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.