Dictionary Merge and Update Operators in Python 3.9#

When it comes to merging two dictinaries in Python, I find myself googling “how to merge two dictionaries” very often. Every time I land on this StackOverflow answer. This answers recommends using the dictionary unpacking feature:

x = {'earth': 5.97, 'mercury': 0.330}
y = {'uranus': 86.8, 'mars': 0.642, 'earth': -999}
a = {**x, **y}
{'earth': -999, 'mercury': 0.33, 'uranus': 86.8, 'mars': 0.642}

Even though I have seen dictionary unpacking used for unpacking keyword arguments in functions, I’ve rarely seen it being used as a method for merging dictionaries, and this makes it a bit confusing if you haven’t seen it used in this context. I was delighted when I found out that Python 3.9 introduced a dedicated binary operator that permits merging two dictionaries. In Python 3.9, we can use the | (bitwise OR) to perform a dictionary merge:

b = x | y
{'earth': -999, 'mercury': 0.33, 'uranus': 86.8, 'mars': 0.642}

As you can see, the resulting dictionary consists of a new dictionary with all the keys of both x and y dictionaries. Because x and y have overlapping key earth, the new dictionary uses the values from the rightmost dictionary (i.e. y)

If we prefer to update one of the dictionary inplace (i.e. without needing to create a new dictionary), we can use the |= (in-place bitwise OR) operator

x |= y
{'earth': -999, 'mercury': 0.33, 'uranus': 86.8, 'mars': 0.642}

I really dig this new | operator. I find the syntax easy to remember and understand compared with the dictionary unpacking feature that I used prior to Python 3.9. There’s one problem though. This operator is only available for Python 3.9+ and I have to write code for older versions of Python for the time being 😞.