another answers here comments
#python で値を持った既存の辞書に、デフォルト値つきの辞書をマージする例 ( もう if 'key' in dict なんて書きたくないんですよ‥ ) - Qiita
Using collections defaultdict and ChainMap together
wanna do
- This dictionary
d = {"a":1, "b",2}
- When calling this way
d["c"]
- I want the default value to be entered instead of 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
ps
- Maybe we aren't doing something really careless
- Please write from the white goat if something is wrong
Original by Github issue
チャットメンバー募集
何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。