Sort items in the dictionary according to the size of the dictionary

Source: Internet
Author: User

Case 1:
The results of a class of Chinese subjects are stored in a dictionary form: {"Lili": "Wenwen": 91 ...}
Calculate students ' rankings according to their grades

Solution:
Using built-in functions sorted
1. Convert dictionary data to tuples using zip
2, pass the key parameter of the sorted function

# EG_V1 using Zip to convert dictionary data into tuples

From random import Randintstud = {X:randint (60,100) to X in "ABCDEFGHJK"} # Create a random transcript dictionary print (stud) # {' A ':, ' B ': the ' d '  : A, ' J ': ", ' e ':", ' F ':------' h ': $, ' G ': +, ' C ': +, ' K ': 90}print (Stud.keys ()) # Get the Dictionary key # Dict_keys ([' A ', ' B ', ' d ', ' J ', ' e ', ' f ', ' h ', ' G ', ' C ', ' K ']) print (Stud.values ()) # Get the value of the dictionary # Dict_keys ([' A ', ' B ', ' d ', ' j ', ' e ', ' f ', ' h ', ' G ', ' C ') , ' K ']) z = Zip (stud.values (), Stud.keys ()) print (sorted (z)) # [(A, ' G '), (+, ' C '), (g, ' E '), (K, ' F '), (--), (87, ' d ') B '), (A-G, ' a '), (+, ' K '), (+, ' H '), (A, ' J ')]

  

# EG_V2 Pass the key parameter of the sorted function

From random import randintrest = {X:randint (60,100) to X in "ABCDEFGHJK"} # Create a random transcript dictionary print (rest) # {' H ': +, ' j ': Up, ' B ': $, ' G ': +, ' F ': +, ' K ': Bayi, ' d ': ", ' e ':", ' C ': ", ' A ': 61}print (Rest.items ()) # Dict_items (' J ', 95 ), (' B ', +), (' G ', +), (' F ', '), (' K ', "Bayi"), (' d ', '), (' E ', '), (' C ', '), (' A ', ') ') result = sorted (Rest.items (), Ke  y = lambda x:x[1]) print (Result) # [(' A ', ' a '), (' F ', ' K '), (' E ', ' G '), (' d ', '), (' K ', ', '), (' C ', ' Bayi '), (' J ', 95), (' h ', +), (' B ', 97)]

  

Sort items in the dictionary according to the size of the dictionary

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.