Python中的有序字典 [英] Ordered Dictionary in Python

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

问题描述

我在Python中有一个像这样的字典: dict = {'a':1,'q':1,'l':2,'m':1,'u':1,'i':1}

I have a Dictionary in Python such as this: dict = {'a':1, 'q':1, 'l':2, 'm':1, 'u':1, 'i':1}

有什么办法可以保持此字典以这种方式表示的顺序.我已经阅读了几个论坛,其中大多数建议使用OrderedDict().但正如这里所解释的:

Is there any way that I can keep the order of this dictionary expressed this way. I have read already several forums and most of them suggest using OrderedDict(). But as explained here:

Python OrderedDict不保持元素顺序

OrderedDict(dict)将不保留顺序.我无法以特定方式手动创建字典(例如元组列表),因为它是由其他地方的代码随机生成的. 非常感谢您的帮助!

OrderedDict(dict) will not keep the order when the dictionary is written in that form. I can not manually create the dictionary in an specific way (e.g list of tuples) because it is randomly generated by the code elsewhere. Thank you very much for you help!!

推荐答案

编写dict = {'a':1, 'q':1, 'l':2, 'm':1, 'u':1, 'i':1}的那一刻,您已经失去了元素的顺序.保持它的方法:

The moment you write dict = {'a':1, 'q':1, 'l':2, 'm':1, 'u':1, 'i':1}, you already have lost the order of the elements. The ways to keep it:

a.首先根据您的数据创建OrderedDict.

a. Create OrderedDict from your data in the first place.

b.将您的dict转换为元组列表,并以所需的方式进行排序,然后从中创建OrderedDict.

b. Convert your dict to a list of tuples and sort in a way you want, then create OrderedDict from it.

总而言之,从您的问题出发,不清楚您想要保留什么.如果它是随机地"生成的,那么谁在乎,如果背后有某种逻辑,则可以使用该逻辑来重新创建该顺序并使用它创建OrderedDict.如果在幕后发生了一些事情,这些事情是根据某些输入数据创建该字典的,那么,a,您看到的顺序不是其创建的顺序.

All in all, from your question it is not clear what you want to preserve. If it is generated "randomly" then who cares, if there is some logic behind it, then use this logic to recreate that order and create OrderedDict using it. If there is something happening behind the scenes which creates this dict from some input data, then, alas, the order in which you see it is not the order in which it has been created.

PS并且不要称呼您的字典dict.

PS And don't call your dict dict.

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

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