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