Home > Net >  How do I sort a dictionary by value with the key as a tie-breaker?
How do I sort a dictionary by value with the key as a tie-breaker?

Time:01-27

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

CodePudding user response:

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}

CodePudding user response:

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} 
  •  Tags:  
  • Related