【问题标题】:Maintain insertion order when merging Python dictionaries合并 Python 字典时保持插入顺序
【发布时间】:2021-08-19 12:12:40
【问题描述】:

我读到 Python 3.6+ 维护字典插入顺序。如果我合并 2 个 python 字典:

x = {"a":5, "d":3}
y = {"c":1, "b":2}
z = x | y

这是否确保 z 中的项目处于准确的插入顺序,即 z 现在是

{"a":5, "d":3, "c":1, "b":2}

如果没有,我怎样才能得到我想要的 z?

【问题讨论】:

标签: python python-3.x dictionary merge


【解决方案1】:

是的,它确保了插入顺序

引入此语法的 PEP PEP 584 列出了运算符的行为,并通过示例实现显示了其语义:

def __or__(self, other):
    if not isinstance(other, dict):
        return NotImplemented
    new = dict(self)
    new.update(other)
    return new

自从引入插入顺序字典以来,dict.update 已被指定以保持其参数的插入顺序,因此x | y 其中x 和y 也是字典。

【讨论】:

    猜你喜欢
    • 2018-05-31
    • 2015-08-05
    • 2010-12-09
    • 2020-11-01
    • 1970-01-01
    • 2010-10-15
    • 2021-11-22
    • 1970-01-01
    • 2011-09-21
    相关资源
    最近更新 更多