DEV Community

Swastik Baranwal
Swastik Baranwal

Posted on

7 3

Python: Merging and Updating Dicts the New Way

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}
Enter fullscreen mode Exit fullscreen mode

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}
Enter fullscreen mode Exit fullscreen mode

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!

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (1)

Collapse
 
delta456 profile image
Swastik Baranwal

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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay