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:
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:
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 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]])
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}