Python中如何按键排序字典 [英] How to sort dictionary by key in numerical order Python

查看:131
本文介绍了Python中如何按键排序字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是字典看起来像:

{'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} 

我试过 sorted(self.docs_info.items),但它不起作用。

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

推荐答案

如果你只需要按键排序,那么你已经有95%了。假设你的字典似乎被称为 docs_info

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)

由于字典键始终是唯一的,调用上排序 docs_info.items()(这是一系列元组)等同于仅通过键进行排序。

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.

请记住,包含数字的字符串不直观地排序!例如112小。如果你需要他们按数字排序,我建议使用 int 而不是 str 例如

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






这当然只是改变你访问字典元素,这通常是足够的(因为如果你没有访问它,如果它被排序什么关系)。如果由于某种原因,您需要将dict本身排序,那么您将不得不使用 collections.OrderedDict ,其中记住了项目的顺序插入。所以你可以先排序你的字典(如上),然后从排序的(键值)对中创建一个 OrderedDict


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

这篇关于Python中如何按键排序字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆