Suppose I have a dictionary in python and I sort the keys by values as follows
my_dict = {'a':5, 'b':4, 'c':6, 'd':3, 'e':2}
sorted_list = sorted(my_dict, key=my_dict.get)
sorted_list
['e', 'd', 'b', 'a', 'c']
This works fine, but if I have collisions in my dictionary (with respect to values)
my_dict = {'a':5, 'b':4, 'c':5, 'd':3, 'e':2, 'f':4, 'g':3}
sorted_list = sorted(my_dict, key=my_dict.get)
sorted_list
['e', 'd', 'g', 'b', 'f', 'a', 'c']
It seems to me that in case of duplicates, the list is sorted by its order(numerical order or insertion order, not the sorted order) in the dictionary. Can I assume it to be true for all cases?
EDIT1: My keys will be integers and in case the values collide, I want the resulting keys to be sorted by their values(highest first)
EDIT2: Adding the following parameter helps my question. But, in my case, I want the values to be sorted in ascending, but the keys to be sorted in descending. THe following will result in both to descending
key=lambda x: (x[1],x[0])
Python’s sort algorithm (TimSort) is a stable sort, so any items that have the same sort ‘value’, are kept in the order they were in before sorting.
When sorting dictionary keys, that means they are kept in the same order as returned by
dict.keys()or when iterating over the dictionary. Do note that this ordering is arbitrary, and not stable across changes to the dictionary.Otherwise yes, you can assume that to be true for all cases.
As pointed out by Steven Rumbalski, you can take the key along with the sorting to stabilize same-value sorting ordering: