DEV Community

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!

Discussion (5)

pic
Editor guide
Collapse
yujiri8 profile image
Ryan Westlund

This is so cool!

Collapse
hanpari profile image
Pavel Morava

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.

Collapse
delta456 profile image
Swastik Baranwal Author

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

Collapse
hanpari profile image
Pavel Morava • Edited

No need to say anything 😁

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