I have a dictionary:
a = {'100':12,'6':5,'88':3,'test':34, '67':7,'1':64 }
I want to sort this dictionary with respect to key so it looks like:
a = {'1':64,'6':5,'67':7,'88':3, '100':12,'test':34 }
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.
Like everyone else has pointed out, dictionaries have their own ordering and you can’t just sort them like you would a list.
One thing I would like to add is that, if you just want to go through the elements of a dictionary in sorted order, that’s just:
If you’d rather have a list comprehension (per Alex):
I would like to point out that Alex’s use of
key=intwon’t work with your example because one of your keys is'test'. If you really want he numbers sorted before the non-numerics, you’ll have to pass in acmpfunction:Or maybe you know enough about your keys to write a function to convert them into a string (or other object) that sorts right:
This would be much faster than using a
cmpfunction.