I have a dictionary d for which the keys are all strings. Now when I do:
for key in d:
print(d[key])
I get the elements of d is some "random" order. How can I force the element of d to come out sorted by the lexicographical order?
Sort before iterating.
for key in sorted(d):
Use sorted() to sort any iterable, including a dictionary:
for key in sorted(d):
print(d[key])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With