Python: Merging and Updating Dicts the New Way
Swastik Baranwal
Posted on April 15, 2020
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!
💖 💪 🙅 🚩
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.