Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maintain insertion order when merging Python dictionaries

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?

like image 235
goober Avatar asked Jan 26 '26 07:01

goober


1 Answers

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.

like image 81
Jasmijn Avatar answered Jan 27 '26 21:01

Jasmijn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!