How to sort dictionary by key in numerical order Python

If you only need to sort by key, you’re 95% there already. Assuming your dictionary seems to be called docs_info:

for key, value in sorted(docs_info.items()): # Note the () after items!
    print(key, value)

Since dictionary keys are always unique, calling sorted on docs_info.items() (which is a sequence of tuples) is equivalent to sorting only by the keys.

Do bear in mind that strings containing numbers sort unintuitively! e.g. "11" is “smaller” than "2". If you need them sorted numerically, I recommend making the keys int instead of str; e.g.

int_docs_info = {int(k) : v for k, v in docss_info.items()}

This of course just changes the order in which you access the dictionary elements, which is usually sufficient (since if you’re not accessing it, what does it matter if it’s sorted?). If for some reason you need the dict itself to be “sorted”, then you’ll have to use collections.OrderedDict, which remembers the order in which items were inserted into it. So you could first sort your dictionary (as above) and then create an OrderedDict from the sorted (key, value) pairs:

sorted_docs_info = collections.OrderedDict(sorted(docs_info.items()))

Leave a Comment