7-3 (c) displays the keys and values in the dictionary in alphabetical order.
Def sortdict (dict1): ValueList = dict1.values () ValueList. sort () dict2 = {} for value in ValueList: for key in dict1: If dict1 [Key] = value and key not in dict2: # prevent repeated output of print key, value, dict2 [Key] = value if _ name __= = "_ main _": dict1 = {'C': 4, 'A': 5, 'Hi ': 78, 'D': 5, 'r': 5} sortdict (dict1)
7-5userpw.py
Def olduser (): promt = "login (case-insensitive):" While true: Name = raw_input (promt). Lower () Nam = set (name) if Nam-valid! = Set ([]): promt = 'invalid char, try another: 'Continue if name not in db. Keys (): info = raw_input ('new user? (Y/n )'). lower () If Info = 'y': Pwd = raw_input ('passwd: ') DB [name] = (md5.new (PWD )). hexdigest () DBT [name] = time. localtime () return else: promt = 'invalid user, try another: '# continue else: Break Pwd = raw_input ('passwd:') passwd = dB. get (name) If passwd = (md5.new (PWD )). hexdigest (): Print 'Welcome back % s' % name last = time. mktime (DBT [name]) Now = time. mktime (time. localtime () If now-last <3600*4: lastime = time. st Rftime ("% Y-% m-% d % H: % m: % s", DBT [name]) print "you already logged in at: % S. "% lastime DBT [name] = time. localtime () else: Print 'login incrrect!'