0
original = ["aga", "aaa", "aba"]

dict = {
    "aba": 1,
    "aaa": 0,
    "aga": 1
}

I need to sort by dict values and tie breakers need to keep original order, how would I do that? Example very simplified.

I tried:

final = sorted(sorted(original, key=lambda x: (dict[x]), key=original.index))
rrebase
  • 3,349
  • 2
  • 16
  • 27
  • 1
    why not using `collections.OrderedDict` directly? – Jean-François Fabre Apr 03 '17 at 16:20
  • 1
    I was under the impression that the built-in sort method _does_ preserve original order in the case of ties. `sorted(original, key=lambda x: (dict[x]))` gives `['aaa', 'aga', 'aba']`. Is that not what you want? If not, can you give the exact desired contents of `final`? – Kevin Apr 03 '17 at 16:29
  • Possible duplicate of [Python sorting list of dictionaries by multiple keys](http://stackoverflow.com/questions/1143671/python-sorting-list-of-dictionaries-by-multiple-keys) – Prune Apr 03 '17 at 16:40
  • Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation. [on topic](http://stackoverflow.com/help/on-topic) and [how to ask](http://stackoverflow.com/help/how-to-ask) apply here. Most notably, *research*. "Python sort tutorial" would answer this for you much more effectively than we can. – Prune Apr 03 '17 at 16:41

2 Answers2

6

Just sort them based on their value in the dictionary. The original order will be preserved for ties:

final = sorted(original, key=dct.get)
print final
# ['aaa', 'aga', 'aba']

Timsort - Python's standard sorting algorithm - is stable; items that compare equal retain their relative order.

On another note, do not use names like dict or list to avoid making builtins unusable later on in your code.

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
0

Dictionaries in Python don't store original order. However, you could use an OrderedDict instead to maintain the order you wish:

import collections
d = collections.OrderedDict()
d['aba'] = 1
d['aaa'] = 0
d['aga'] = 1
print(d)
Neil
  • 14,063
  • 3
  • 30
  • 51