Suppose I have a dictionary like this:
{'t': 1, 's': 2, 'f': 2, 'q': 3}
If I want to rearrange keys in alphabetical order for pairs with equal value, how should I do it in Python?
so it can look like:
{'t': 1, 'f': 2, 's': 2, 'q': 3}
Suppose I have a dictionary like this:
{'t': 1, 's': 2, 'f': 2, 'q': 3}
If I want to rearrange keys in alphabetical order for pairs with equal value, how should I do it in Python?
so it can look like:
{'t': 1, 'f': 2, 's': 2, 'q': 3}
dict.items()
returns the key-value pairs, so we can sort those by value first, and key second, using the ordering semantics of tuples, which orders tuples element-by-element, so it is ordered first by the ordering of all first elements, then by the second elements, etc.:
a = {'t': 1, 's': 2, 'f': 2, 'q': 3}
a_sorted = dict(sorted(a.items(), key=lambda x: (x[1], x[0])))
Do note that order for dict
s is only guaranteed to be maintained in Python 3.7+, in older versions you'd have to use collections.OrderedDict
:
from collections import OrderedDict
a = {'t': 1, 's': 2, 'f': 2, 'q': 3}
a_sorted = OrderedDict(sorted(a.items(), key=lambda x: (x[1], x[0])))