我读到 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
哪里x
和 y
是字典呢。
关于python - 合并Python字典时保持插入顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67786422/