1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Python 3.9のdictのマージ(`|`)が便利っぽい

Last updated at Posted at 2020-08-06

概要

Python3.9からdictがマージできるようになったようす。
| でできるようす。

使ったPython

Python 3.9.0b5 (default, Aug  6 2020, 10:04:28)
[Clang 12.0.0 (clang-1200.0.26.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

試してみます

基本的な使い方

>>> a = {'a1': 1}
>>> b = {'b1': 1}
>>> a | b
{'a1': 1, 'b1': 1}

マージと代入

>>> a = {'a1': 1}
>>> b = {'b1': 1}
>>> a |= b
>>> a
{'a1': 1, 'b1': 1}

同じキーがあったとき

>>> a1 = {'a': 1, 'b': 1}
>>> a2 = {'a': 2, 'b': 2, 'c': 2}
>>> a1 | a2
{'a': 2, 'b': 2, 'c': 2}
>>> a2 | a1
{'a': 1, 'b': 1, 'c': 2}

ちょっと込み入ったdict

>>> d1 = {'a': 1, 'b': {'c': 2}}
>>> d2 = {'z': 999}
>>> d1 | d2
{'a': 1, 'b': {'c': 2}, 'z': 999}
>>> d1 = {'a': 1, 'b': {'c': 2}}
>>> d2 = {'z': 999, 'b': {'c': 888}}
>>> d1 | d2
{'a': 1, 'b': {'c': 888}, 'z': 999}

まとめ

すこぶる簡単にしか試していませんが便利っぽいです

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?