New features in Python 3.9 (1)-Union operators can be used in dictionary types

Introduction

New changes in Python 3.9 scheduled to be released in October 2020 are summarized in the article What's new in Python 3.9 (Summary) started. I decided to cut out a relatively large amount of items in another article, but as the first step, I would like to take up the change that makes it possible to use the union operator in the dictionary type.

Dictionary-type integration

The dictionary type is one of the standard data types built into Python. In other languages, it is called various types such as hash type, map type, and associative array type, but the point is that it is a data type for storing name / value pairs (key-value pairs).

Consider that there are two dictionary-type data (d1, d2) and they are mixed into one dictionary-type data. There have been several ways to do this.

1) Use the ʻupdate` method

If you do d1.update (d2) `, the integrated dictionary type data will be overwritten and stored in d1. If you want to keep d1 as it is

e = d1.copy()
e.update(d2)

You need to make a copy and then call the ʻupdate` method. It's a little troublesome.

2) Take out the contents and arrange them

As {** d1, ** d2}, the contents data is fetched from each dictionary type and returned in a new dictionary type. You can get integrated dictionary data without intermediate variables, but it's hard to tell what you're doing by looking at Pat. Even Guido, the original author of Python, is so confusing that he says, "I forgot that there was such a way" (laughs).

3) Use collections.ChainMap

The collections module has a class called ChainMap, and if you use dict (ChainMap (d2, d1)), you can get integrated dictionary data. The tricky part is that, unlike the example above, if you have the same key, the one on the left has priority. Although standard, you have to import the collections module, and this method isn't very intuitive either.

4) Use a dictionary-type constructor

There is dict (mapping, ** kwarg) in the dictionary type constructor, so if you use this to make dict (d1, ** d2), you will get integrated dictionary type data. By setting ** d2, the contents of d2 are given as keyword arguments and added to the contents of the first argument ( d1 does not change). The problem with this method is that the contents of d2 are given as keyword arguments, so it can only be integrated if the key is a string dictionary type.

Union operator and dictionary type

For operators used in Set type|When|=There is, for example, you can use it like this.

>>> a = set((1,2,3))
>>> b = set((3,4,5))
>>> a | b
{1,2,3,4,5}
>>> a |= b
>>> a
{1,2,3,4,5}

It is a union operator because it calculates the "sum" of two sets. Let's use this union operator for the integration of dictionary data, which is a change scheduled to enter 3.9 this time.

The specification is very simple, and the sum of the two dictionary type data is taken like the Set type. The difference from Set is the correspondence when the keys overlap, and even if the Set overlaps, it is only necessary not to count twice, but in the case of the dictionary type, there are values as well as keys, so which one to use Becomes a problem. With this change, the value on the right side of the formula is prioritized. It's an image of overlapping in order from the left and overwriting the ones with the same key.

It's faster to see it as an example.

>>> c = {'a': 1, 'b': 2}
>>> d = {'b': 3, 'c': 7}
>>> c | d
{'a': 1, 'b': 3, 'c': 7}
>>> d | c
{'a': 1, 'b': 2, 'c': 7}
>>> c |= d
>>> c
{'a': 1, 'b': 3, 'c': 7}

Herec | dWith the result ofd | cThe fact that the result of is different (not commutative) is unpleasant as an operator of "sum", but you can only think of it as such.

Summary

Let's explain the union operator that will be introduced in the dictionary type in Python 3.9 based on the contents of PEP-584. I did. I think that I used to use dict.update in many cases, but since it destroys the original dictionary type, I think there are various uses for drawing immutable operations in easy-to-understand notation.

Recommended Posts

New features in Python 3.9 (1)-Union operators can be used in dictionary types
Japanese can be used with Python in Docker environment
Operators ++,-cannot be used in python (difference from php)
Can be used in competition pros! Python standard library
Scripts that can be used when using bottle in Python
Python standard input summary that can be used in competition pro
New features in Python 3.4.0 (3)-Single-dispatch generic functions
I wrote a tri-tree that can be used for high-speed dictionary implementation in D language and Python.
++ and-cannot be used for increment / decrement in python
File types that can be used with Go
Functions that can be used in for statements
I made a familiar function that can be used in statistics with Python
Basic algorithms that can be used in competition pros
[Memorandum] Japanese keys cannot be used in python string.Template.substitute
ANTs image registration that can be used in 5 minutes
list comprehension because operator.methodcaller cannot be used in python 2.5
What's new in Python 3.5
New in Python 3.4.0 (1)-pathlib
Non-linear simultaneous equations can be easily solved in Python.
Organize types in Python
What's new in Python 3.6
[Redash] Standard library cannot be used in python function
Can be used with AtCoder! A collection of techniques for drawing short code in Python!
[Python3] Code that can be used when you want to resize images in folder units
[Python] Variadic arguments can be used when unpacking iterable elements
Goroutine (parallel control) that can be used in the field
Goroutine that can be used in the field (errgroup.Group edition)
SSD 1306 OLED can be used with Raspberry Pi + python (Note)
Pharmaceutical company researchers have summarized the operators used in Python
Create a dictionary in Python
What's new in Python 3.10 (Summary)
Avoid KeyError in python dictionary
What's new in Python 3.4.0 (2) --enum
What's new in Python 3.9 (Summary)
Nesting ternary operators in python
New Python grammar and features not mentioned in the introductory book
33 strings that should not be used as variable names in python
A timer (ticker) that can be used in the field (can be used anywhere)
Investigating what could be used as a Markdown parser in Python
[Python] Why immutable int types can be changed to different values
Python standard module that can be used on the command line
Notes on Python and dictionary types
What's new in python3.9 Merge dictionaries
8 Frequently Used Commands in Python Django
[Python] Basic knowledge used in AtCoder
Easy padding of data that can be used in natural language processing
I created a template for a Python project that can be used universally
Study from Python Hour6: Frequently used data types: tuple type, set type, dictionary type
gRPC-Methods used when dealing with protocol buffers types in Python CopyFrom, Extend
Mathematical optimization that can be used for free work with Python + PuLP