I'm quite late to the party, but if, like me, you've stumbled upon this page via [your favorite search engine], I'd like to be the one to give you the good news:
While Python dicts will never be naturally sorted, it's trivial to use them as if they are. Assuming that your keys are, in fact, integers, simply pass your favorite dict, D
, to the sorted
built-in like so:
for index, item in sorted(D.items()):
print("index:", index, "item:", item)
D.items()
returns a class dict_items
with an __iter__
method which, when called, as by the for
or in
statements, returns an iterator, yielding key-value pairs, which can be iterated over like any other iterable.
sorted
takes the iterator and returns a list, so if D = {1: "alpha", 3: "charlie", 2: "bravo"}
, then what is returned by sorted
is the sorted list [(1, "alpha"), (2, "bravo"), (3, "charlie")]
.
It's also possible to sort by a specific element:
sorted(D.items(), key=lambda x: x[1])
Or by some other, arbitrary, even nondeterministic, sorting criterion:
sorted(D.items(), lambda _: random.randint(0, 100))
The construction of the list from the dict is an operation O(n) in time and space, and Python's sorting algorithm, Timsort, is very efficient (O(n log n) in the average case), so in the vast majority of real-world use cases, runtime performance isn't something worth worrying about.