Python basics------How to "sort" dictionaries based on dictionary values

Source: Internet
Author: User

Requirements: Dictionary of {name: score}, sorted by score

Method One: Convert to Tuples, (91, "Zhang San") in the form of the sorted () function to sort

Method Two: Set the value of the key parameter in sorted ()

1 #-*-coding:utf-8-*-2 #mister into a random dictionary3  fromRandomImportRandint4d= {x:randint (60,101) forXinch "abcdxyz"}5 Print(d)6 #method One: Tuple form7 #Put the value in front because the sorted () sort by default is compared from the beginning8z =Zip (d.values (), D.keys ())9 #x = Zip (D.itervalues (), D.iterkeys ()) iteration type, save spaceTen #Sort Ones =sorted (z) A Print(s) -  - #method Two: sorted (key setting) theA =D.items () -s = sorted (a,key=LambdaX:x[1]) - Print(s)

Python basics------How to "sort" dictionaries based on dictionary values

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.