关于python:collections.OrderedDict作为普通的dict语法

collections.OrderedDict as normal dict syntax

本问题已经有最佳答案,请猛点这里访问。

在不将现有的dict转换为使用[(key, value), ..., ]的情况下,是否可以使用collections.OrderedDict作为普通dict语法,使用某种from __???__ import ???派生?我在代码中嵌入了几个JSON,希望保持顺序。


没有collections.OrderedDict,就有可能有一个有序的字典:只需升级到python 3.6。

来自PEP 468,业绩不佳:

Note: in Python 3.6 dict is order-preserving. This virtually eliminates performance concerns.

只要用一本普通字典就行了。

1
2
3
4
5
6
Python 3.4.2 (v3.4.2:ab2c023a9432, Oct  6 2014, 22:16:31) [MSC v.1600 64 bit (AMD64)] on win32
Type"help","copyright","credits" or"license" for more information.
>>> {1:1, 2:2}
{1: 1, 2: 2}
>>> {2:2, 1:1}
{1: 1, 2: 2}
1
2
3
4
5
6
Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)] on win32
Type"help","copyright","credits" or"license" for more information.
>>> {1:1, 2:2}
{1: 1, 2: 2}
>>> {2:2, 1:1}
{2: 2, 1: 1}