简体   繁体   中英

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

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

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}

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} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM