How does the Python language implement dictionary ordering?

Source: Internet
Author: User
Xinhua dictionary Everyone has used it, then how to use the Python language is to implement the dictionary sort? Follow this tutorial to learn the Python implementation of the dictionary based on the value sort, need a friend to refer to it

The specific contents are as follows:

Use sorted to sort dictionaries by their value size

>>> record = {' A '::100}>>>, ' B ': sorted, ' C ': The ", ' d '," (Record.items (), Key=lambda x:x[1]) [(' B ', 86), (' A ', ","), (' C ', "), (' d ', 100)]

Sorted the first parameter can be iterated, it can be a tuple, a list

>>> items = [(1, ' B '), (1, ' a '), (2, ' a '), (0, ' B '), (0, ' a ')]>>> sorted (items) [(0, ' B '), (0, ' a '), (1, ' A '), (1, ' B '), (2, ' a ')]

Why (0, ' B ') in front of (0, ' a ')?

Because uppercase letters in ASCII code precede lowercase letters, use the Str.lower () method to change their order

>>> sorted (items, Key=lambda x: (X[0], X[1].lower ()))
[(0, ' a '), (0, ' B '), (1, ' a '), (1, ' B '), (2, ' a ')]

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.