3

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?

goober
  • 99
  • 4
  • 4
    Did you try merging the two dictionaries and seeing what the result was? – Kemp Jun 01 '21 at 09:41
  • Does this answer your question? [How do I merge two dictionaries in a single expression (taking union of dictionaries)?](https://stackoverflow.com/questions/38987/how-do-i-merge-two-dictionaries-in-a-single-expression-taking-union-of-dictiona) – queste Jun 01 '21 at 09:44
  • Is there a reason you're bothered about the insertion order at all? dictionaries arent designed to be sorted. `OrderedDict` may be better for you – Sayse Jun 01 '21 at 09:44
  • 1
    @Kemp yes, just want to make sure it's generalizable. – goober Jun 01 '21 at 10:31
  • 1
    @queste this other question doesn't address the order of the resulting dictionary. – goober Jun 01 '21 at 10:32
  • 1
    @Sayse see [here](https://stackoverflow.com/questions/50872498/will-ordereddict-become-redundant-in-python-3-7) – goober Jun 01 '21 at 10:32

1 Answers1

3

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.

Jasmijn
  • 9,370
  • 2
  • 29
  • 43