Python 使用其构造函数初始化 OrderedDict 以使其保留初始数据顺序的正确方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25480089/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:16:51  来源:igfitidea点击:

Right way to initialize an OrderedDict using its constructor such that it retains order of initial data?

pythonsortingdictionaryordereddictionary

提问by click

What's the correct way to initialize an ordered dictionary (OD) so that it retains the order of initial data?

初始化有序字典(OD)以保留初始数据顺序的正确方法是什么?

from collections import OrderedDict

# Obviously wrong because regular dict loses order
d = OrderedDict({'b':2, 'a':1}) 

# An OD is represented by a list of tuples, so would this work?
d = OrderedDict([('b',2), ('a', 1)])

# What about using a list comprehension, will 'd' preserve the order of 'l'
l = ['b', 'a', 'c', 'aa']
d = OrderedDict([(i,i) for i in l])

Question:

题:

  • Will an OrderedDictpreserve the order of a list of tuples, or tuple of tuples or tuple of lists or list of lists etc. passed at the time of initialization (2nd & 3rd example above)?

  • How does one go about verifying if OrderedDictactually maintains an order? Since a dicthas an unpredictable order, what if my test vectors luckily have the same initial order as the unpredictable order of a dict? For example, if instead of d = OrderedDict({'b':2, 'a':1})I write d = OrderedDict({'a':1, 'b':2}), I can wrongly conclude that the order is preserved. In this case, I found out that a dictis ordered alphabetically, but that may not be always true. What's a reliable way to use a counterexample to verify whether a data structure preserves order or not, short of trying test vectors repeatedly until one breaks?

  • 是否会OrderedDict保留在初始化时传递的元组列表、元组元组或列表元组或列表等的顺序(上面的第二个和第三个示例)?

  • 如何验证是否OrderedDict实际维护订单?由于 adict具有不可预测的顺序,如果我的测试向量幸运地具有与 dict 的不可预测顺序相同的初始顺序怎么办?例如,如果不是d = OrderedDict({'b':2, 'a':1})我写d = OrderedDict({'a':1, 'b':2}),我可以错误地得出保留顺序的结论。在这种情况下,我发现 adict是按字母顺序排列的,但这可能并不总是正确的。什么是使用反例来验证数据结构是否保持顺序的可靠方法,而不是反复尝试测试向量直到一个中断?

P.S. I'll just leave this here for reference: "The OrderedDict constructor and update() method both accept keyword arguments, but their order is lost because Python's function call semantics pass-in keyword arguments using a regular unordered dictionary"

PS 我将把它留在这里以供参考:“OrderedDict 构造函数和 update() 方法都接受关键字参数,但它们的顺序丢失了,因为 Python 的函数调用语义使用常规无序字典传入关键字参数”

P.P.S : Hopefully, in future, OrderedDict will preserve the order of kwargs also (example 1): http://bugs.python.org/issue16991

PPS:希望将来,OrderedDict 也将保留 kwargs 的顺序(示例 1):http: //bugs.python.org/issue16991

采纳答案by BrenBarn

The OrderedDict will preserve any order that it has access to. The only way to pass ordered data to it to initialize is to pass a list (or, more generally, an iterable) of key-value pairs, as in your last two examples. As the documentation you linked to says, the OrderedDict does not have access to any order when you pass in keyword arguments or a dict argument, since any order there is removed before the OrderedDict constructor sees it.

OrderedDict 将保留它有权访问的任何订单。将有序数据传递给它进行初始化的唯一方法是传递键值对的列表(或更一般地说,一个可迭代的),如前两个示例所示。正如您链接到的文档所说,当您传入关键字参数或 dict 参数时, OrderedDict 无法访问任何订单,因为在 OrderedDict 构造函数看到之前删除了任何订单。

Note that using a list comprehension in your last example doesn't change anything. There's no difference between OrderedDict([(i,i) for i in l])and OrderedDict([('b', 'b'), ('a', 'a'), ('c', 'c'), ('aa', 'aa')]). The list comprehension is evaluated and creates the list and it is passed in; OrderedDict knows nothing about how it was created.

请注意,在上一个示例中使用列表理解不会改变任何内容。OrderedDict([(i,i) for i in l])和之间没有区别OrderedDict([('b', 'b'), ('a', 'a'), ('c', 'c'), ('aa', 'aa')])。对列表理解进行评估并创建列表并将其传入;OrderedDict 对它是如何创建的一无所知。

回答by metatoaster

# An OD is represented by a list of tuples, so would this work?
d = OrderedDict([('b', 2), ('a', 1)])

Yes, that will work. By definition, a list is always ordered the way it is represented. This goes for list-comprehension too, the list generated is in the same way the data was provided (i.e. source from a list it will be deterministic, sourced from a setor dictnot so much).

是的,这会奏效。根据定义,列表总是按照它的表示方式排序。这也适用于列表理解,生成的列表与提供数据的方式相同(即来自列表的来源它将是确定性的,来自setdict不那么多)。

How does one go about verifying if OrderedDictactually maintains an order. Since a dict has an unpredictable order, what if my test vectors luckily has the same initial order as the unpredictable order of a dict?. For example, if instead of d = OrderedDict({'b':2, 'a':1})I write d = OrderedDict({'a':1, 'b':2}), I can wrongly conclude that the order is preserved. In this case, I found out that a dictis order alphabetically, but that may not be always true. i.e. what's a reliable way to use a counter example to verify if a data structure preserves order or not short of trying test vectors repeatedly until one breaks.

如何验证是否OrderedDict实际维护订单。由于 dict 具有不可预测的顺序,如果我的测试向量幸运地具有与 dict 的不可预测顺序相同的初始顺序怎么办?例如,如果不是d = OrderedDict({'b':2, 'a':1})我写d = OrderedDict({'a':1, 'b':2}),我可以错误地得出保留顺序的结论。在这种情况下,我发现 adict是按字母顺序排列的,但这可能并不总是正确的。即使用反例来验证数据结构是否保持顺序或不重复尝试测试向量直到一个中断的可靠方法是什么。

You keep your source list of 2-tuple around for reference, and use that as your test data for your test cases when you do unit tests. Iterate through them and ensure the order is maintained.

您保留 2 元组的源列表以供参考,并在进行单元测试时将其用作测试用例的测试数据。遍历它们并确保保持顺序。