python - 合并Python字典时保持插入顺序

标签 python python-3.x dictionary merge

我读到 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?

最佳答案

是的,它确保广告订单
引入此语法的 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哪里xy是字典呢。

关于python - 合并Python字典时保持插入顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67786422/

相关文章:

python - 将两个 Python try/except block 压缩为一个而不改变行为

python - 在 Windows 7 上安装 hg-git,使用 MinGW 编译

python - 根据其他列的条件在 python 中创建数据框列

c++ - 作为键的 vector 如何在 C++ 内部工作?

c# - 从 Enum 创建字典<Enum, int>

python - 如何在 Blender 2.64 中导入 wxPython 模块?

Python 3 CSV 文件给出 UnicodeDecodeError : 'utf-8' codec can't decode byte error when I print

python - 如何在 Windows 中设置 PYTHONPATH?

python - 更改默认响应内容类型的正确方法

python 3 : sum (union) of dictionaries with "+" operand raises exception