acclivity

pySortDictByValue

Oct 26th, 2020 (edited)
202
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.74 KB | None | 0 0
  1. # Find the dictionary entry with 2nd highest associated value
  2.  
  3. my_dict = {'a': 10, 'c': 30, 'b':20, 'd':40, 'g': 25}
  4. listv = list(my_dict.values())               # extract a list of value from the dictionary
  5. listk = list(my_dict.keys())                 # extract a list of keys from the dictionary
  6. # Note: there might be a direct way of extracting value+key pairs, but I've not found it yet
  7. listboth = list(zip(listv, listk))           # gives a list of tuples, being value,key pairs
  8. listsorted = sorted(listboth, reverse=True)  # this seems to sort by value (1st entry in tuple)
  9. mytuple = listsorted[1]                      # extract the tuple for 2nd highest value
  10. print("2nd largest value is for dictionary key", mytuple[1], "value", mytuple[0])
Add Comment
Please, Sign In to add comment