How do I sort a dictionary by its keys?
Example input:
{2:3, 1:89, 4:5, 3:0}
Desired output:
{1:89, 2:3, 3:0, 4:5}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Standard Python dictionaries are unordered (until Python 3.7). Even if you sorted the (key,value) pairs, you wouldn’t be able to store them in a
dictin a way that would preserve the ordering.The easiest way is to use
OrderedDict, which remembers the order in which the elements have been inserted:Never mind the way
odis printed out; it’ll work as expected:Python 3
For Python 3 users, one needs to use the
.items()instead of.iteritems():