How to Sort a Dictionary using Python
Dictionaries in Python are unordered data structures. However, there are instances where sorting a dictionary by its keys is necessary.
Example Input:
{2:3, 1:89, 4:5, 3:0}
Desired Output:
{1:89, 2:3, 3:0, 4:5}
Standard Python Dictionaries
Standard Python dictionaries maintain key order only as of Python version 3.7. Prior to version 3.7, using the sorted(d.items()) function will not achieve the desired result as these dictionaries do not preserve the order of the sorted pairs.
OrderedDict
For versions prior to Python 3.7, the solution is to use the OrderedDict class from the collections module. This class stores key-value pairs in the order in which they are inserted, ensuring a consistent ordering.
import collections d = {2:3, 1:89, 4:5, 3:0} # Create an OrderedDict from sorted key-value pairs od = collections.OrderedDict(sorted(d.items())) print(od)
Output:
OrderedDict([(1, 89), (2, 3), (3, 0), (4, 5)])
Python 3
For Python versions 3 and above, the .items() method should be used instead of .iteritems():
for k, v in od.items(): print(k, v)
Output:
1 89 2 3 3 0 4 5
The above is the detailed content of How to Sort a Python Dictionary by Keys?. For more information, please follow other related articles on the PHP Chinese website!