python 3.5中的dict.popitem()

Jos*_*ita 2 python dictionary python-3.x

在 Python 的最新版本中,内置字典 {} 保留了顺序,就像 OrderedDict 一样(即使不能保证这样做)。

dict.popitem() 总是从字典中返回最后一个键值对,还是随机一个?

iBu*_*Bug 5

是的。来自Python 文档(3.7):

弹出项()

从字典中删除并返回一个 (key, value) 对。对按 LIFO 顺序返回。

这同样适用collections.OrderedDictPython 3.7 之前的版本。

但是,请注意dict.popitem(无序版本)在 Python 3.6 或更旧版本中没有保证。