🖥

Example of using defaultdict to prevent KeyError in # python's nested

2019/04/15に公開

<h1> example </h1>

<ul>
<li> Nesting and using defaultdict in layers </li>
<li> I can not get angry if I write a nonexistent key like <code>d["x"]["y"]["z"]</code> </li>
<li> Maybe a good girl may not be imitating </li>
</ul>

<pre> <code class="py">>>> from collections import defaultdict
>>> d = defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: 0)))
>>> d["a"]["b"]["c"] = 1
>>> d["a"]["b"]["c"]
1
>>> d["x"]["y"]["z"]
0
</code> </pre>

<h1> If you write in ruby </h1>

<p> It was such a feeling. This is also a good girl. </p>

<pre> <code class="rb">[27] pry(main)> h = Hash.new(Hash.new(Hash.new(0)))
=> {}
[28] pry(main)> h["a"]["b"]["c"] = 1
=> 1
[29] pry(main)> h["a"]["b"]["c"]
=> 1
[30] pry(main)> h["x"]["y"]["z"]
=> 0
</code> </pre>

<h1> ref </h1>

<p> <a href="https://qiita.com/xza/items/72a1b07fcf64d1f4bdb7">How to use Python defaultdict-Qiita</a> </p>

Original by Github issue

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

チャットメンバー募集

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

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

Twitter

https://twitter.com/YumaInaura

公開日時

2019-04-15

Discussion