Skip to content

Python 3.9 Dict Merge and Update

header
Python 3.9 Dict Merge and Update Operations ===========================================

Python 3.9 was released on Oct 5, 2020 (2020-10-05 for programming purposes), and with it there are several new features.  This post will be one of several short posts showing off those changes.

Dict Merge

Merging two dicts is something you may need to do when you have data coming from multiple sources and would like to only have a single dict to use in your application.  It has become very easy in Python 3.9.  Let's take a look at that now.

To merge two dicts we'll simple use the pipe (|) operator:



x = {"word1": "Hello", "word2": "World", "word3": "!"}
y = {"word2": "from", "word3": "Python3.9"}

>>> x
{'word1': 'Hello', 'word2': 'World', 'word3': '!'}
>>> y
{'word2': 'from', 'word3': 'Python3.9'}
>>> x | y
{'word1': 'Hello', 'word2': 'from', 'word3': 'Python3.9'}

As you can see the word2 and word3 elements are updated with the values from the y dict to create a single new dict with the merged keys.

Dict Update

Updating a dict with the values from another dict is also made easier in Python 3.9.  To update a dict you'll use the update command (|=) and the original dict will be updated with the values from the second dict.  Let's take a look:


>>>> x = {"word1": "Hello", "word2": "World", "word3": "!"}
>>> y = {"word2": "from", "word3": "Python3.9"}
>>> x
{'word1': 'Hello', 'word2': 'World', 'word3': '!'}
>>> y
{'word2': 'from', 'word3': 'Python3.9'}
>>> x | y
{'word1': 'Hello', 'word2': 'from', 'word3': 'Python3.9'}

>>> x |= y
>>> x
{'word1': 'Hello', 'word2': 'from', 'word3': 'Python3.9'}

With these small changes Python has become easier to use and understand.  I hope this helps you out and if you have any feedback please let me know by leaving a comment.