-1

For instance, if I sorted:

{3:4, 4:5, 5:5, 7:2}

I would expect:

{7:2, 3:4, 4:5, 5:5}

Note: This is not a duplicate of other 'how to sort a dictionary' questions because they do not show how to use the key as a tie-breaker.

Related:

How do I sort a dictionary by value?

Python 3 list sorting with a tie-breaker

martineau
  • 112,593
  • 23
  • 157
  • 280
DivideByZero
  • 383
  • 4
  • 13
  • See the [The Old Way Using Decorate-Sort-Undecorate](https://docs.python.org/3/howto/sorting.html#the-old-way-using-decorate-sort-undecorate) section of the [Sorting HOW TO](https://docs.python.org/3/howto/sorting.html#sorting-how-to) in the fine documentation. It (also) explains why the technique described is not often needed because of Python's key-functions. – martineau Jan 27 '22 at 00:44

2 Answers2

4

You can sort d.items(). Since it's key-value tuples, the second elements are values and first elements are keys.

out = dict(sorted(d.items(), key=lambda x: (x[1], x[0])))

Output:

{7: 2, 3: 4, 4: 5, 5: 5}
0

If the keys are already in order, you can leverage the fact that Python's sort is stable (keeps original order for same value sort key):

{k:d[k] for k in sorted(d,key=d.get)}

{7: 2, 3: 4, 4: 5, 5: 5} 
Alain T.
  • 34,859
  • 4
  • 30
  • 47