What's new in python3.9 Merge dictionaries

What's new in python3.9 Merge dictionaries

Overview

Python 3.9 was released on October 05, 2020. One of the new features this time is the dict merge operator. This merge operator makes it easier than ever to merge dictionaries.

Trial environment construction (Docker required)

You can run Python 3.9 on a Docker container by following the steps below. The following steps work on a Docker container so you can validate Python 3.9 without updating the Python version of your host.

1. Create an account for docker hub (only if you don't have an account).

2. docker login from the terminal

$ docker login
Login with your Docker ID to push and pull images from Docker Hub. If you don't have a Docker ID, head over to https://hub.docker.com to create one.
Username: #Enter your docker hub username here and press Enter
Password: #Enter the docker hub password here and press Enter

If the following display appears, login is successful

Login Succeeded

3. Pull python3.9 Docker image from docker hub

$ docker pull python:3.9
 3.9: Pulling from library/python
e4c3d3e4f7b0: Pull complete 
101c41d0463b: Pull complete 
8275efcd805f: Pull complete 
751620502a7a: Pull complete 
0a5e725150a2: Pull complete 
397dba5694db: Pull complete 
b1d09d0eabcb: Pull complete 
475299e7c7f3: Pull complete 
d2fe14d8e6bc: Pull complete 
Digest: sha256:429b2fd1f6657e4176d81815dc9e66477d74f8cbf986883c024c9b97f7d4d5a6
Status: Downloaded newer image for python:3.9
docker.io/library/python:3.9

4. Start the container from docker image and start Python in the container in interactive mode

$ docker run -it python:3.9 python3
Python 3.9.0 (default, Oct 13 2020, 20:14:06)  # ←Python3.9 is running
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

Merge operator

Consider the case of combining two dictionaries to make one dictionary.

>> dict_1 = {"name": "Alice", "age": 29}
>> dict_2 = {"mail": "[email protected]", "tel": "000-0000-0000"}

#Combine the above two dicts to make the following dict
dict_3 = {'name': 'Alice', 'age': 29, 'mail': '[email protected]', 'tel': '000-0000-0000'}

In traditional Python, looping through dict items and assigning dict_2 elements to dict_1 one by one.

>> dict_3 = dict_1.copy() # dict_3 = dict_1 is dict_Note that 1 is also rewritten
>>> for key, value in dict_2.items():
...   dict_3[key] = value
...
>>> dict_3
{'name': 'Alice', 'age': 29, 'mail': '[email protected]', 'tel': '000-0000-0000'}
>>> dict_1
{'name': 'Alice', 'age': 29} #Dict after merging_1 does not change
>>> dict_2
{'mail': '[email protected]', 'tel': '000-0000-0000'} #Dict after merging_2 does not change

In Python 3.9, the above process is completed only by the merge operator.

>>> dict_3 = dict_1 | dict_2 # |Is the merge operator
>>> dict_3
{'name': 'Alice', 'age': 29, 'mail': '[email protected]', 'tel': '000-0000-0000'}

By using the merge operator, the process of merging dict_1 and dict_2 can be described in one line. If the same key exists in two dicts, the merged value will be on the right-hand side (last win).

>>> dict_1 = {"name": "Alice", "age": "29"}
>>> dict_2 = {"mail": "[email protected]", "tel": "000-0000-0000", "age": 30} # "age"Is dict_1 and dict_Included in both 2
>>> dict_1 | dict_2
{'name': 'Alice', 'age': 30, 'mail': '[email protected]', 'tel': '000-0000-0000'} #age is dict_It has become 2
>>> dict_1 = {"name": "Alice", "age": "29"}
>>> dict_2 = {"mail": "[email protected]", "tel": "000-0000-0000", "age": None}
>>> dict_1 | dict_2
{'name': 'Alice', 'age': None, 'mail': '[email protected]', 'tel': '000-0000-0000'} #Note that even if the value on the right side is None, it will be included in the dictionary after merging.(Not the value on the left side)

Merge operator assignment statement

As with other operators such as + and-, you can assign the merged dict to the left side by adding =.

>>> dict_1 = {"name": "Alice", "age": 29}
>>> dict_2 = {"mail": "[email protected]", "tel": "000-0000-0000"}
>>> id(dict_1), id(dict_2)
(140606638257856, 140606638701760)
>>> dict_1 |= dict_2 # dict_1 and dict_Dict the result of merging 2_Substitute to 1
>>> dict_1
{'name': 'Alice', 'age': 29, 'mail': '[email protected]', 'tel': '000-0000-0000'} # dict_1 is rewritten
>>> dict_2
{'mail': '[email protected]', 'tel': '000-0000-0000'} # dict_2 does not change
>>> id(dict_1), id(dict_2)
(140606638257856, 140606638701760) #id is the same before and after the operation

Merge operator and OrderedDict

The merge operator can also be used for OrderedDict.

>>> from collections import OrderedDict
>>> o_dict_1 = OrderedDict({'name': 'Alice', 'age': 29})
>>> o_dict_2 = OrderedDict({'mail': '[email protected]', 'tel': '000-0000-0000'})
>>> o_dict_1
OrderedDict([('name', 'Alice'), ('age', 29)])
>>> o_dict_1 | o_dict_2
OrderedDict([('name', 'Alice'), ('age', 29), ('mail', '[email protected]'), ('tel', '000-0000-0000')])

If there is a key common to the left side and the right side, the order is the left side and the value is the right side. Keys contained only on the right side are added to the end in the order of the right side.

>>> from collections import OrderedDict
>>> o_dict_1 = OrderedDict({'name': 'Alice', 'age': 29})
>>> o_dict_2 = OrderedDict({'mail': '[email protected]', 'age': 30, 'name': 'Bob', 'tel': '000-0000-0000'})
>>> o_dict_1 | o_dict_2
OrderedDict([('name', 'Bob'), ('age', 30), ('mail', '[email protected]'), ('tel', '000-0000-0000')])
# age,name is o_dict_O in order of 1_dict_They are lined up with a value of 2.
# dict_Mail included only in 2,tel is o_dict_Added to the end in the order of 2

Recommended Posts

What's new in python3.9 Merge dictionaries
What's new in Python 3.5
What's new in Python 3.6
What's new in Python 3.10 (Summary)
What's new in Python 3.4.0 (2) --enum
What's new in Python 3.9 (Summary)
New in Python 3.4.0 (1)-pathlib
What's new in datetime that is a bit more useful in Python 3
New in Python 3.9 (2)-Sort directed acyclic graphs in Python
What's new in Django 1.8 Conditional Expressions #djangoja
New features in Python 3.4.0 (3)-Single-dispatch generic functions
Quadtree in Python --2
Python in optimization
CURL in python
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
SendKeys in Python
Meta-analysis in Python
Unittest in python
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
N-Gram in Python
Programming in python
Plink in Python
Constant in python
pandas 1.2.0 What's new
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
StepAIC in Python
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
Constant in python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Quad-tree in Python
Reflection in Python
Chemistry in Python
Hashable in python
DirectLiNGAM in Python
LiNGAM in Python
Flatten in python
flatten in python
A memo about writing merge sort in Python
I want to merge nested dicts in Python
Create a new page in confluence with Python
Sorted list in Python
Daily AtCoder # 36 in Python
Clustering text in Python