相当于 Python 中的 LinkedHashMap
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/653887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Equivalent for LinkedHashMap in Python
提问by dmeister
LinkedHashMapis the Java implementation of a Hashtable like data structure (dict in Python) with predictable iteration order. That means that during a traversal over all keys, they are ordered by insertion. This is done by an additional linked list maintaining the insertion order.
LinkedHashMap是具有可预测迭代顺序的类似 Hashtable 的数据结构(Python 中的 dict)的 Java 实现。这意味着在遍历所有键的过程中,它们按插入排序。这是由维护插入顺序的附加链表完成的。
Is there an equivalent to that in Python?
是否有与 Python 中的等价物?
采纳答案by Eli Courtwright
If you're on Python 2.7 or Python >=3.1 you can use collections.OrderedDictin the standard library.
如果您使用的是 Python 2.7 或 Python >=3.1,您可以在标准库中使用collections.OrderedDict。
This answerto the question How do you retrieve items from a dictionary in the order that they're inserted?contains an implementation of an ordered dict, in case you're not using Python 3.x and don't want to give yourself a dependency on the third-party ordereddict module.
这个答案的问题你如何检索顺序字典项目,他们正在插入?包含有序 dict 的实现,以防您不使用 Python 3.x 并且不想让自己依赖于第三方ordersdict 模块。
回答by sykora
Although you can do the same thing by maintaining a list to keep track of insertion order, Python 2.7and Python >=3.1have an OrderedDict class in the collections module.
尽管您可以通过维护一个列表来跟踪插入顺序来做同样的事情,但Python 2.7和Python >=3.1在 collections 模块中有一个 OrderedDict 类。
Before 2.7, you can subclass dict
following this recipe.
在 2.7 之前,您可以dict
按照此配方进行子类化。
回答by aatifh
I am not sure whether this is what you are asking for:
我不确定这是否是您的要求:
>>> dic = {1: 'one', 2: 'two'}
>>> for k, v in dic.iteritems():
... print k, v
you can order the dic in the order of the insertion using ordereddictmodule.
您可以使用ordereddict模块按插入顺序对dic进行排序。
d = ordereddict(dic, relax=True)
回答by DNS
I don't think so; you'd have to use a dict plus a list. But you could pretty easily wrap that in a class, and define keys
, __getitem__
, __setitem__
, etc. to make it work the way you want.
我不这么认为;你必须使用一个字典加上一个列表。但是你可以很容易地包裹在一个类,并定义keys
,__getitem__
,__setitem__
等,使其工作你想要的方式。
回答by ?sa Kilikya
In addition to the validated comment;
除了经过验证的评论;
As of Python 3.7, dict
preserves insertion order.
从 Python 3.7 开始,dict
保留插入顺序。
This answershows this with details.
这个答案详细说明了这一点。