Python Dictionary multi-Conditional Ordering Method Example

Source: Internet
Author: User
In the process of writing a project, you can always find the sort of dictionary, and if you want to implement a multi-conditional sort, you only need the following lines of code to implement. Fully embodies the benefits of Python.
Copy the Code code as follows:


Teamitems = [{' Team ': ' France ', ' P ': 1, ' GD ': -3, ' GS ': 1, ' GA ': 4},
{' Team ': ' Uruguay ', ' P ': 7, ' GD ': 4, ' GS ': 4, ' GA ': 0},
{' Team ': ' SouthAfrica ', ' P ': 4, ' GD ': -2, ' GS ': 3, ' GA ': 5},
{' Team ': ' Mexico ', ' P ': 4, ' GD ': 1, ' GS ': 3, ' GA ': 2}]

Print sorted (teamitems, key = lambda x: (x[' P '],x[' GD '],x[' GS '],x[' GA '), reverse=true)


The above code implemented by pressing ' P ', ' GD ', ' GS ', ' GA ' four conditional sorting, reverse=true for descending

Of course I can.
Copy the Code code as follows:


From operator Import Itemgetter
Print sorted (teamitems, key = Itemgetter (' P ', ' GD ', ' GS ', ' GA '), reverse=true)
  • 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.