3
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.

PEP 584 (Add Union Operators To dict) を読んだよメモ

Posted at

先日、PEP 584 (Add Union Operators To dict)Final になったというコミットを見かけました。
そこで、今回は PEP 584 を読んでみようと思います。

概要

  • ふたつの辞書を結合するいい感じの方法がほしい
    • d1.update(d2) は d1 を書き換えてしまうため、一時変数を用意する場面があるし、式ではないのでパラメータにしていできない
    • {**d1, **d2} ってキモい
    • collections.ChainMap はマイナーな上に、 d1 を書き換える問題がある
    • dict(d1, **d2) はキーが文字列以外の場合にエラーになる
  • 辞書の結合に | 演算子を使えるようにする
  • Python 3.9 から利用できます

アプローチ

d1 | d2 でふたつの辞書を結合します。同じキーを持つ場合、右の辞書の内容で上書きするので、可換ではありません(新しい辞書のキーの順序も変わります)。

>>> d = {'spam': 1, 'eggs': 2, 'cheese': 3}
>>> e = {'cheese': 'cheddar', 'aardvark': 'Ethel'}
>>> d | e
{'spam': 1, 'eggs': 2, 'cheese': 'cheddar', 'aardvark': 'Ethel'}
>>> e | d
{'aardvark': 'Ethel', 'spam': 1, 'eggs': 2, 'cheese': 3}

一緒に |= 演算子にも対応しました。

>>> d |= e
>>> d
{'spam': 1, 'eggs': 2, 'cheese': 'cheddar', 'aardvark': 'Ethel'}

感想

  • 違和感はあるのだけど、しばらくしたら慣れてくるはず。たぶん…
  • d = dict(d1); d.update(d2) は何度も書いたことがあるので、嬉しさはわかる
  • スッキリ書けるのはいいですね
3
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
3
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?