For some reason, sorting a dictionary by its keys seems to be one of the most frequently asked Python questions. I'm not sure if this is because it's just much easier to do in other languages, or if the semantics of the language just confuse new Python developers. I guess the reason for confusion really isn't as important as the answer.
I think the easiest way to return a list of keys in sorted order is with the
sorted()
function:
sorted(dict.keys())
You can use this directly in a loop such as:
for key in sorted(dict.keys()):
print key
If you need to sort in reverse order, add the reverse=True
parameter:
for key in sorted(dict.keys(), reverse=True):
print key
This works in basic cases. Hopefully, that will be enough to get you started.