Step up your Python knowledge with 4 new statements

Python 3.9 has been around since late 2020 and it comes with a bunch of new syntax features and improvements. In this article, we are going to explore a few nice additions which were packed into this version. We will also discuss how to upgrade to Python 3.9 in case you want to.
- Merging Dictionaries
As of Python 3.9, you can use the |
operator to merge two or more dictionaries together. For duplicate keys the rightmost dictionary takes precedence. This syntactic sugar is part of PEP-584.

>>> dict1 = {'a': 1, 'b': 2}
>>> dict2 = {'b': 3, 'c': 4, 'd': 5}
>>> dict1 | dict2
{'a': 1, 'b': 3, 'c': 4, 'd': 5}
- Updating Dictionaries
Going a step forward, you can also use |=
operator to update a dictionary in-place. Essentially a |= b
is equivalent to a = a | b
but |=
won’t return a new dictionary but a
will be modified instead. This addition is also part of PEP-584.

>>> dict1 = {'a': 1, 'b': 2}
>>> dict2 = {'b': 3, 'c': 4, 'd': 5}
>>> dict1 |= dict2
>>> dict1
{'a': 1, 'b': 3, 'c': 4, 'd': 5}
- Removing a Prefix From Strings
String method removeprefix()
can now be used to remove the prefix from strings.
This new additions is part of PEP-616.

>>> my_str = 'Title: Hello World'
>>> my_str.removeprefix('Title: ')
Hello World
- Removing a Suffix From Strings
The second addition packed into PEP-616 is the removesuffix()
string method. Like the previous example, this method can be used to remove the suffix from strings.

>>> my_str = 'Title: Hello World'
>>> my_str.removesuffix(' Hello World')
Title:
How to Install Python 3.9
In order to install Python 3.9 I would advise you to do so using the official downloads provided in the documentation. There are even a few minor updates to 3.9.0 – make sure to see the latest version(s) available here.
If you are a Windows or OSX user simply download the corresponding file from the first link I provided.
If you are a Linux user you can install it through APT:
$ sudo apt update
$ sudo apt install software-properties-common
$ sudo add-apt-repository ppa:deadsnakes/ppa
$ sudo apt install python3.9
On every platform you should be able to verify that Python 3.9 has been successfully installed by running python --version
in the terminal or command-line (depending on your os).
Conclusion
In this article, we discussed a few recent additions in Python 3.9. We showcased how to use |
and |=
operators to merge and update dictionaries. Additionally, we introduced two new string methods namely removeprefix()
and removesuffix()
that can be applied over strings to remove the prefix or suffix respectively. Finally, we quickly explored how to install or update (to) Python 3.9.
If you want to learn about more features and improvements that were part of version 3.9, see the official release highlights.
You may also be interested in: