【发布时间】:2014-03-03 23:52:38
【问题描述】:
在哪里可以找到有关最向前/向后兼容的字典方法的信息?例如,在 python 2.5 之后没有变化并且在 python3 中也将被支持的东西?
例如:我不确定d.itervalues() 是否是一种向后/向前兼容的方法?我用它从字典中获取单个元素:
# is this good form for those who care about compatibility?
d = {"foo": {"bar": []}}
elt = next(d.itervalues())
【问题讨论】:
-
字典在 Python 中没有顺序。
elt可能会因相同的dict而不同运行。要以向后/向前兼容的方式从没有six.itervalues()的字典中获取 some 值:d[next(iter(d))]。顺便说一句,next()builtin 仅在 Python 2.6+ 中可用 -
@JFSebastian:我可以满足于 2.6+ 的支持,所以如果
next(iter(d))在 Python 3 中工作并且不需要将整个列表加载到内存中看起来不像,那么这就是答案
标签: python python-3.x dictionary compatibility backwards-compatibility