+1 vote
in Programming Languages by (39.4k points)
I want to sort a dictionary by its keys. Is there any Pythonic way for it?

1 Answer

+2 votes
by (66.8k points)
selected by
 
Best answer

You can use the sorted() function to sort a dictionary by its keys. It will return a list of tuples that can be converted to a dictionary using the dict() function.

Here is an example:

>>> aa={'a':12, 'e':34, 'c':45, 'b':13, 'g':22, 'd':10}

>>> sorted(aa.items())

[('a', 12), ('b', 13), ('c', 45), ('d', 10), ('e', 34), ('g', 22)]

>>> dict(sorted(aa.items()))

{'a': 12, 'b': 13, 'c': 45, 'd': 10, 'e': 34, 'g': 22}

 

You can also use OrderedDict() function from the collections module.
>>> from collections import OrderedDict
>>> OrderedDict(sorted(aa.items(), key=lambda x: x[0]))
OrderedDict([('a', 12), ('b', 13), ('c', 45), ('d', 10), ('e', 34), ('g', 22)])
>>> dict(OrderedDict(sorted(aa.items(), key=lambda x: x[0])))
{'a': 12, 'b': 13, 'c': 45, 'd': 10, 'e': 34, 'g': 22}

...