loading...

Python: Merging and Updating Dicts the New Way

delta456 profile image Swastik Baranwal ・1 min read

In the upcoming Python version 3.9 you can now merge and update Dictionaries by simply using | for merging and |= and for updating.

Merge Dictionaries by | operator

dict1 = {'Sam' : 15, 'Peter' : 27, 'John': 35, 'Ben' : 42} 
dict1 = {'Mark' : 15, 'Tom' : 27, 'Jack': 24, 'Ben' : 34}
dict3 = dict1 | dict2 
print(dict3)
#Ouput: {'Sam' : 15, 'Peter' : 27, 'John': 35, 'Ben' : 34, 'Mark' : 15, 'Tom' : 27, 'Jack': 24}

Just like update() the latter one's common key is combined with the new dict.

Update Dictionaries by |= operator

dict1 = {'Sam' : 15, 'Peter' : 27, 'John': 35, 'Ben' : 42} 
dict1 |= Dict({'Mark' : 15, 'Tom' : 27, 'Jack': 24, 'Ben' : 34})
print(dict1)
#Ouput: {'Sam' : 15, 'Peter' : 27, 'John': 35, 'Ben' : 34, 'Mark' : 15, 'Tom' : 27, 'Jack': 24}

Just like the previous one the latter one's common key is combined with the new dict.

If you are an experienced Pythonic Programmer you already would have guessed that it uses | and |= operator overloading.

Python 3.9 is scheduled to be released in this October!

Posted on Dec 4 '19 by:

Discussion

markdown guide
 

That's sweet syntactic sugar, sprinkled on top of an already generously topped doughnut (or something like that)...

I think that these two new operators (to me at least) looks very "visually" logical.
It's kinda like using "pipes" in *nix commands, as in:

# dict3 is the result of dict1 being 'piped' through dict2, resulting in a union of these.
dict3 = dict1 | dict2

That is awesome.

Maybe even more awesome, the augmented assignment version, |= operates in-place.
Where one would have resorted to using the awkward update() method and create a temporary as well, something that undoubtedly felt rather clunky, in 3.9 this is one expression, which updates dict1 in-place, no need for any temporary throw-away object.

The question that popped up first was "Hmm, but what about the cases where you get overlapping keys as a result? This would obviously crash the party.

But, thankfully, key conflicts will be resolved by keeping the rightmost value.
This matches the existing behavior of similar dict operations and keeps things consistent and clean.

Way to go Python!

 
 

Not a lucky decision and design. The operator | is a union operation for sets, which is commutative operation.

Using for dicts breaks mathematics. It is as wrong as using + string concatenation.

 

I don't know what to say. It's opinionated.

 

No need to say anything 😁

I just wanted to point out why it might not be such a great idea.