Python 中的有序字典是什么?
pythonserver side programmingprogramming更新于 2025/8/14 1:16:17
OrderedDict 是一个字典子类,它可以记住其内容的添加顺序,支持常见的 dict 方法。如果新条目覆盖现有条目,则原始插入位置保持不变。删除条目并重新插入会将其移至末尾。
>>> from collections import OrderedDict
>>> d = {'banana': 3, 'apple':4, 'pear': 1, 'mango': 2}
>>> od=OrderedDict(d.items())
>>> od
OrderedDict([('banana', 3), ('apple', 4), ('pear', 1), ('mango', 2)])
>>> od=OrderedDict(sorted(d.items()))
>>> od
OrderedDict([('apple', 4), ('banana', 3), ('mango', 2), ('pear', 1)])
>>> t=od.popitem()
>>> t
('pear', 1)
>>> od=OrderedDict(d.items())
>>> t=od.popitem()
>>> t
('mango', 2)
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

