-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
  • 119,623
  • 25
  • 170
  • 301
DivideByZero
  • 423
  • 6
  • 14
  • 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

3 Answers3

7

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}
1

If you want to sort dict by it's values and then by keys as a tie breaker then use following code :

here key = lambda consist of dict value = (x[1]) as well as dict key = (x[0])

d= {3:4, 4:5, 5:5, 7:2}    # or any other dict

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

o/p : [(7, 2), (3, 4), (4, 5), (5, 5)]

So you can change the sequence as per your need for example if you want to sort by keys first then values then use this:

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

If you want the sorting in reverse for values and then by keys then use this:

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

If you want to reverse any one of the values or keys then use negative sign accordingly

One last thing [] or () both work fine in lambda function

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

sorted(d.items() , key=lambda x: [x[1],x[0]])
Shilpa Shinde
  • 961
  • 8
  • 10
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.
  • 40,517
  • 4
  • 31
  • 51