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!

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (1)

Collapse
 
delta456 profile image
Swastik Baranwal

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

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

Okay