🖥

Example of merging a dictionary with default values into an existing d

2019/04/15に公開

another answers here comments

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


<p> Using collections defaultdict and ChainMap together </p>

<h1> wanna do </h1>

<ul>
<li> This dictionary <code>d = {"a":1, "b",2}</code> </li>
<li> When calling this way <code>d["c"]</code> </li>
<li> I want the default value to be entered instead of KeyError </li>
</ul>

<h1> example </h1>

<pre> <code class="py">from collections import defaultdict
import collections

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

default_dict = defaultdict(int)

merged_dict = collections.ChainMap(existing_dict, default_dict)
</code> </pre>

<h1> EXE </h1>

<pre> <code class="py">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
</code> </pre>

<h1> ps </h1>

<ul>
<li> Maybe we aren't doing something really careless </li>
<li> Please write from the white goat if something is wrong </li>
</ul>

Original by Github issue

https://github.com/YumaInaura/YumaInaura/issues/1291

チャットメンバー募集

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

https://line.me/ti/g2/eEPltQ6Tzh3pYAZV8JXKZqc7PJ6L0rpm573dcQ

Twitter

https://twitter.com/YumaInaura

公開日時

2019-04-15

Discussion