Python: Merging and Updating Dicts the New Way

delta456

Swastik Baranwal

Posted on April 15, 2020

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!

💖 💪 🙅 🚩
delta456
Swastik Baranwal

Posted on April 15, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related