Simpler Updating of Dictionaries
Here are additional resources about PEP 584 and dictionaries:
The second is the pipe equals operator that acts like the
.update() function call. Let me start by showing you the old way of doing things. In order to do that, I’m going to need a couple of dictionaries. This first one is PyCon events, and the second one is EuroPython events.
You can create new dictionaries using the double asterisks operator (
**). This example creates a third dictionary called
merged, which constitutes
pycon is untouched,
europython is untouched, and
merged is the mix of the two of them.
This results in the same thing. You could also have achieved this with the
.update() function. But keep in mind,
.update() operates on the existing dictionary, so now
pycon has both the original and the
europython entries inside of it.
Pay close attention to where the parentheses are in this example. The first set of parentheses surround the walrus operator.
(merged := pycon.copy()) calls
pycon.copy(), returns the result into
merged, and then the walrus operator returns the value of
merged into the expression.
So the inside of the parentheses is the value of
merged after the
.update() is then run on that value. You can see the result here. Just because you’ve got a result doesn’t mean it was pretty getting there. Python 3.9 has introduced the pipe operator to make cleaner-looking code to solve the same kind of problem.
So, the pipe operator acts as a merge. The pipe equals operator acts as an update. This time,
pycon has been updated to include both the values it had before, as well as the values from
Now, if I use the double asterisk operator (
**) from before, it’ll work, but it won’t still be a
defaultdict. The result is a regular dictionary. Fortunately, the pipe operator is aware of the class.
Unlike the other mechanism, with the double asterisk operator, the pipe operator actually returns a
defaultdict with the merged results. The operators are also aware of other ways of constructing dictionaries.
05:34 And now I can or-equals the kinds of things that you put in a dictionary constructor, like a list of tuples. The end result is an updated dictionary. This gives you power as to how you can update your dictionary, and still do it with clean-looking code.
Notice that both of these dictionaries have a key called
"Georgia". If I merge
usa first, the dictionary in the second part, i.e. the
usa in this case, overwrites the keys in the first part.
The only exception is they haven’t been added to the abstract base classes. Like many operators in Python, these have been implemented using dunder methods:
.__ior()__, for pipe and pipe equals, respectively. Because these are implemented as functions, you can override them and change the behavior yourself.
Become a Member to join the conversation.