I read that Python 3.6+ maintains dictionary insertion order. If I merge 2 python dictionaries:
x = {"a":5, "d":3}
y = {"c":1, "b":2}
z = x | y
Does this ensure that the items in z are in the exact insertion order, i.e. z would now be
{"a":5, "d":3, "c":1, "b":2}
If not, how can I get my desired z?
Yes, it ensures insertion order
The PEP which introduced this syntax, PEP 584, lays out the behaviour of the operator, with an example implementation that shows its semantics:
def __or__(self, other):
if not isinstance(other, dict):
return NotImplemented
new = dict(self)
new.update(other)
return new
Since the introduction of insertion-ordered dictionaries, dict.update has been specified to keep the insertion order of its arguments, and thus x | y where x and y are dictionaries does too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With