Python dictionary multi-condition sorting method example

Source: Internet
Author: User

When writing a project, you can always sort the dictionary. To achieve multi-conditional sorting, you only need the following lines of code. This fully demonstrates the benefits of python.
Copy codeThe Code is as follows:
Teamitems = [{'team': 'France ', 'P': 1, 'gd':-3, 'gs ': 1, 'ga': 4 },
{'Team': 'uruguay', 'P': 7, 'gd ': 4, 'gs': 4, 'gal': 0 },
{'Team': 'southfrica ', 'P': 4, 'gd':-2, 'gs ': 3, 'gal': 5 },
{'Team': 'mico ', 'P': 4, 'gd': 1, 'gs ': 3, 'gal': 2}]

Print sorted (teamitems, key = lambda x :( x ['P'], x ['gd '], x ['gs'], x ['ga ']), reverse = True)
The preceding Code sorts data by 'P', 'gd ', 'gs', and 'ga '. reverse = True indicates descending order.

Yes, of course.
Copy codeThe Code is as follows:
From operator import itemgetter
Print sorted (teamitems, key = itemgetter ('P', 'gd ', 'gs', 'ga '), reverse = True)

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.