-1

Python 3.9 adds in the Dictionary Merge (|) & Update Operators (|=) announcement

What are the differences between the two? What -- if any -- differences are there between the update operator and dict.update?

hrokr
  • 3,276
  • 3
  • 21
  • 39
  • A dupe of [this](https://stackoverflow.com/questions/64210846/when-to-use-dictionary-merge-vs-update-operator) post, but that's not a great target. I swear there was a good post covering this. – Carcigenicate Nov 03 '20 at 18:52
  • 2
    Did you read [the PEP](https://www.python.org/dev/peps/pep-0584/)? If not, do you still have any questions after reading the PEP? – wim Nov 03 '20 at 19:01
  • Does this answer your question? [How do I merge two dictionaries in a single expression in Python (taking union of dictionaries)?](https://stackoverflow.com/questions/38987/how-do-i-merge-two-dictionaries-in-a-single-expression-in-python-taking-union-o) – wwii Nov 03 '20 at 19:04
  • @wim I did, of course. Is there some part of PEP 584 you think answers the question? I certainly don't see it. – hrokr Nov 03 '20 at 19:09
  • 2
    Yes, the [specification](https://www.python.org/dev/peps/pep-0584/#specification) section of the PEP explains exactly what the new operators do and what the differences are, complete with examples. The [motivation](https://www.python.org/dev/peps/pep-0584/#dict-update) section explained the difference with `dict.update`. I don't think your question really shows the level of research effort we expect on stack overflow. – wim Nov 03 '20 at 19:12

1 Answers1

1

These are like other augmented operations. | creates a new dictionary like {**d1, **d2} does. |= updates an existing dictionary like .update.

>>> d1 = {1:1, 3:3}
>>> d2 = {2:2, 3:4}
>>> 
>>> d3 = d1 | d2
>>> d3
{1: 1, 3: 4, 2: 2}
>>> 
>>> d1 |= d2
>>> d1
{1: 1, 3: 4, 2: 2}
tdelaney
  • 73,364
  • 6
  • 83
  • 116