3
0

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 1 year has passed since last update.

#python で値を持った既存の辞書に、デフォルト値つきの辞書をマージする例 ( もう if 'key' in dict なんて書きたくないんですよ‥ )

Last updated at Posted at 2019-04-15

collections の defaultdict と ChainMap を合わせて使う

wanna do

  • こういう辞書を d = {"a":1, "b",2}
  • こう呼び出した時 d["c"]
  • KeyError ではなくデフォルト値が入っていてほしい

example

from collections import defaultdict
import collections

existing_dict = {"a":1, "b":2}

default_dict = defaultdict(int)

merged_dict = collections.ChainMap(existing_dict, default_dict)

exe

Python 3.7.2 (default, Jan 13 2019, 12:50:01)
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections import defaultdict
>>> import collections
>>> existing_dict = {"a":1, "b":2}
>>> default_dict = defaultdict(int)
>>> merged_dict = collections.ChainMap(existing_dict, default_dict)
>>> merged_dict["a"]
1
>>> merged_dict["b"]
2
>>> merged_dict["c"]
0
>>> merged_dict["d"]
0

p.s

  • もしかしたらものすごく迂遠なことをやっていないだろうか
  • 何か変だったら白ヤギさんからお手紙ください

Original by Github issue

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

3
0
8

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?