0

Lets say I have a dictionary:

dict1 = {'a': 3, 'b': 1.2, 'c': 1.6, 'd': 3.88, 'e': 0.72}

I need to be able to sort this by min and max value and call on them using this function I am still writing (note: 'occurences,' 'avg_scores' and 'std_dev' are all dictionaries and 'words' are the dictionary's keys.):

def sort(words, occurrences, avg_scores, std_dev):
    '''sorts and prints the output'''
    menu = menu_validate("You must choose one of the valid choices of 1, 2, 3, 4 \n        Sort Options\n    1. Sort by Avg Ascending\n    2. Sort by Avg Descending\n    3. Sort by Std Deviation Ascending\n    4. Sort by Std Deviation Descending", 1, 4)
    print ("{}{}{}{}\n{}".format("Word", "Occurence", "Avg. Score", "Std. Dev.", "="*51))
    if menu == 1:
        for i in range (len(word_list)):
            print ("{}{}{}{}".format(cnt_list.sorted[i],)

I'm sure I am making this way more difficult on myself than necessary and any help would be appreciated. Thanks!

ryan doucette
  • 83
  • 1
  • 8
  • 1
    Possible duplicate of [Sort a Python dictionary by value](http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value) – Pierre Barre Apr 25 '16 at 02:42

3 Answers3

1

You can sort the keys based on the associated value. For instance:

>>> dict1 = {'a': 3, 'b': 1.2, 'c': 1.6, 'd': 3.88, 'e': 0.72}
>>> for k in sorted(dict1, key=dict1.get):
...   print k, dict1[k]
...
e 0.72
b 1.2
c 1.6
a 3
d 3.88    
chepner
  • 497,756
  • 71
  • 530
  • 681
1

Use min and max with key:

dict1 = {'a': 3, 'b': 1.2, 'c': 1.6, 'd': 3.88, 'e': 0.72}

min_v = min(dict1.items(), key=lambda x: x[1])
max_v = max(dict1.items(), key=lambda x: x[1])

print min_v, max_v
JRazor
  • 2,707
  • 18
  • 27
0

You can't sort a dict, only it's representation. But, you can use an ordereddict instead.

from collections import OrderedDict

dictionnary = OrderedDict(
    sorted(
        {'a': 3, 'b': 1.2, 'c': 1.6, 'd': 3.88, 'e': 0.72
         }.items(), key=lambda x:x[1], reverse=True))
Pierre Barre
  • 2,174
  • 1
  • 11
  • 23
  • 2
    when user312016 says "You can't sort a dict". You can iterate over or create a list of the dictionary values in a sorted manner using the sorted function, but the order of the values in a dictionary is not guaranteed. So what's in there is not sorted, but we can sort it as we are retrieving the values – hostingutilities.com Apr 25 '16 at 02:48