Reputation: 259
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!
Upvotes: 1
Views: 180
Reputation: 61509
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)
Upvotes: 2