【问题标题】:collections.OrderedDict as normal dict syntax [duplicate]collections.OrderedDict 作为普通的dict语法[重复]
【发布时间】:2017-05-14 15:22:18
【问题描述】:

是否可以像普通的字典语法一样使用collections.OrderedDict,使用某种from __???__ import ??? 派生词,而无需将现有字典转换为使用[(key, value), ..., ]?我在代码中有几个嵌入的 json,并希望保持顺序。

【问题讨论】:

  • 我想从普通的 dict 语法构造 collections.OrderedDict。即x={"A":1, "B":2}; assert type(x) == collections.OrderedDict。当然,第二个是False。那么,是否有可能通过某种 hacky 衍生品来实现它?
  • 使用某种文字语法无助于解码 JSON;只需告诉json.loads() 代码在解码时使用OrderedDict。查看副本。

标签: python


【解决方案1】:

完全没有collections.OrderedDict 的有序字典是可能的:只需升级到Python 3.6。

来自PEP 468, under Performance

注意:在 Python 3.6 中,dict 是保序的。这实际上消除了性能问题。

使用普通字典即可。

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}

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}

【讨论】:

  • 好建议,考虑到升级不会破坏他们的代码
  • docs.python.org/3.6/whatsnew/… 声明:'这个新实现的顺序保留方面被认为是一个实现细节,不应依赖'。
  • @hiroprotagonist - 奇怪的是 PEP 只是声明 dict 现在已订购,但 PEP 的摘要说这是一个实现细节。
  • 嗯...这是怎么回事?!如果(pyton 3.6++)实现回到无序的dict,很多代码会中断,因为人们没有准备好dict键无序......
猜你喜欢
  • 1970-01-01
  • 2017-01-22
  • 2021-02-04
  • 1970-01-01
  • 2017-12-24
  • 1970-01-01
  • 1970-01-01
  • 2021-08-26
  • 2011-08-07
相关资源
最近更新 更多