1

Okay so I'm trying to sort a dictionary of key values pairs in a dictionary. The keys are words and values are decimal values. I'm trying to get a list of sorted keys based on the values. right now I have:

sortedList = sorted(wordSimDic, key=wordSimDic.get,reverse=True)

This works. However, I would like to be able to do one thing further. If the values of the keys match I would like them to be sorted in the outputlist by the key in alphabetical order.

For example

    Input:
    {'c':1,'a':1,'d':3}

    Output:
    [a,c,d]

 right now my output is:
    [c,a,d]

Do you have suggestion.Thanks so much!

user3750474
  • 249
  • 5
  • 18
  • Possible duplicate of [Sort a Python dictionary by value](http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value.) – wwii Nov 29 '14 at 05:15
  • 1
    This doesn't seem to be a duplicate; OP seems to have already solved the basic problem from that question, but wants to refine it. – Karl Knechtel Nov 29 '14 at 05:35
  • @KarlKnechtel, ahh yes the details, thank you. – wwii Nov 29 '14 at 06:09
  • I guess then a possible duplicate of [Sort a list by multiple attributes?](http://stackoverflow.com/questions/4233476/sort-a-list-by-multiple-attributes). – wwii Nov 29 '14 at 06:20

1 Answers1

2

In general, to 'sort by X then Y' in Python, you want a key function that produces an (X, Y) tuple (or other sequence, but tuples are simplest and cleanest really). Thus:

sorted(wordSimDic, key=lambda k: (wordSimDic.get(k), k), reverse=True)
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153