Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
985 views
in Technique[技术] by (71.8m points)

sorting - How to sort dictionary by key in numerical order Python

Here is the dictionary looks like:

{'57481': 50, '57480': 89, '57483': 110, '57482': 18, '57485': 82, '57484': 40}  

I would like to sort the dictionary in numerical order, the result should be:

{'57480': 89, '57481': 50, '57482': 18, '57483': 110, '57484': 40, '57485': 82} 

I tried sorted(self.docs_info.items) but it doesn't work.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...