1

In, python3.9, the merge operator (|), is used for merging dictionaries together. Kind of like this:

foo = {1:'spam', 'eggs':2}
bar = {3:'foo', 'eggs':'foo'}
foobar = foo|bar

But how is the merge operator used in python3.8 and lower, besides merging dictionaries together?

theX
  • 1,008
  • 7
  • 22
  • You can look at the PEP here https://www.python.org/dev/peps/pep-0584/#specification – jkr Jul 11 '20 at 01:20

1 Answers1

4

The | operator has magic method __or__. It is also used to express set union (merging), as well as bitwise or.

xavc
  • 1,245
  • 1
  • 8
  • 14
  • Wait, so it is also the `or` operator in python? I thought only the `or` keyword was it – theX Jul 11 '20 at 01:25
  • No, the `or` keyword is distinct from `|` (bitwise or, also used to express union). – xavc Jul 11 '20 at 01:27
  • So, what't the difference between the `bitwise or` and the `or` keyword? – theX Jul 11 '20 at 01:28
  • @theX You can read more at https://wiki.python.org/moin/BitwiseOperators (note the final heading 'Other Classes'). – xavc Jul 11 '20 at 01:29
  • The `or` keyword will evaluate the left hand side expression. If that result is truthy, it will return it, otherwise it will return the right hand side. For example `0b011 | 0b100 == 0b111`, while `0b011 or 0b100 == 0b011` – xavc Jul 11 '20 at 01:31