【问题标题】:Python 3.5 / 3.6 code depending on dict insertion orderPython 3.5 / 3.6 代码取决于 dict 插入顺序
【发布时间】:2018-12-02 15:35:03
【问题描述】:

我在 Python 3.6 上编写了一些代码,我发现这些代码依赖于 3.6 中新增的键的 dict 插入顺序,并将在 3.7 中得到保证。 我想支持3.5。我的文件开头有这个:

import sys
if sys.version_info[1] < 6:
    from collections import OrderedDict
else:
    OrderedDict = dict

这似乎有效。我认为 dict 可能比 OrderedDict 更快,尽管我没有检查这一点。我的问题是,这是这样做的方法,还是出于任何原因有一些更系统/更漂亮/更pythonic或通常更好的方法?

【问题讨论】:

  • 常用功能之间没有具体区别,但OrderDict() 与简单的 dict 相比具有许多额外功能。

标签: python dictionary python-3.5 python-3.6 ordereddictionary


【解决方案1】:

您的解决方案工作正常,但我会提醒不要用其他任何东西替换标准库名称,这可能会使尝试使用 OrederedDict(并发现它只是 dict)的人感到困惑。

我建议这样做:

import sys
if sys.version_info[1] < 6:
    from collections import OrderedDict as ordered_dict
else:
    ordered_dict = dict

【讨论】:

  • 我认为重命名为 ordered_dict 是要走的路。
猜你喜欢
  • 2018-01-12
  • 1970-01-01
  • 2019-02-25
  • 1970-01-01
  • 2019-09-30
  • 2018-11-07
  • 1970-01-01
  • 2016-02-18
  • 1970-01-01
相关资源
最近更新 更多