0

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}
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Tedy
  • 25
  • 3
  • 1
    Is there a reason why you want to rearrange the keys of a dict? That seems very unnecessary and most probably not the right way to go. The purpose of a dict is so you can access data by key value pairs. If you are 'sorting' the keys of a dict you might want to consider a list of tuples. – Jason Chia Mar 25 '21 at 09:22
  • There are arguments for using ordered dictionaries, hence they existed as `collections.OrderedDict` in the standard library. We can only speculate whether @Tedy really needs the ordering, but you cannot say that ordering is not useful per-se when using dicts. I have encountered several situations where ordering is very useful. For example if you want to be able to offer indexing a data structure using both a running index into the dict, and a key. An OrderedDict is perfect for that, and with Python 3.7+ all dicts are ordered _and_ more performant than before. – Jan Christoph Terasa Mar 25 '21 at 09:37
  • I'd love to have an STL-container in C++ with the O(1) lookup and ordering guarantees of Python. – Jan Christoph Terasa Mar 25 '21 at 09:46

1 Answers1

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 dicts 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])))
Jan Christoph Terasa
  • 5,781
  • 24
  • 34