I found a suspicious code snipped in an existing project in which I am involved as a developer. The code sorts a dict
by its keys, so that if iterated over the dict, the elements are returned in the sorted order.
In order to have some stand-alone code I refactored out a function which does that job.
However, as I was suspicious about the existing implementation I wrote a second stand-alone function which does the same job but a little different.
Please review my two implementations from which I will improve the better one given the suggestions and then add it to the project.
The performance and number of statements within the function does not matter so much in this case. However, I need to be sure that the items in the dict
are returned in the correct order when iterating over it.
1.)
def sort_dct1(dct: dict) -> dict:
return dict(sorted(dct.items()))
Test:
print(sort_dct({3: 100, 2: 10, 44: 20, 1: 80})) # just for testing
> {1: 80, 2: 10, 3: 100, 44: 20}
2.)
import collections
def sort_dct2(dct: dict) -> collections.OrderedDict:
return collections.OrderedDict(sorted(dct.items()))
Test:
print(sort_dct2({3: 100, 2: 10, 44: 20, 1: 80}))
> OrderedDict([(1, 80), (2, 10), (3, 100), (44, 20)])
The second implementation also passes the isinstance
test:
isinstance(sort_dct2({3: 100, 2: 10, 44: 20, 1: 80}), dict)
True
(key, value)
pairs. The outcome is still the same as sorting by keys only, since the keys in a dict are guaranteed to be unique, but still... \$\endgroup\$key
andvalue
are standing concepts and I wanted to say that I wanted to sort by the "value" of the keys and not by the "values" in the dict, I should clarify. Will update the question. \$\endgroup\$