🖥

# I want to prevent KeyError using python's defaultdict

2019/04/15に公開

<h1> import </h1>

<pre> <code>>>> from collections import defaultdict
</code> </pre>

<h1> int </h1>

<p> Create a dictionary with default value 0 for any key </p>

<pre> <code class="py">>>> a = defaultdict(int)
>>> a
defaultdict(<class 'int'>, {})
>>> a["1"]
0
>>> a[1]
0
>>> a["a"]
0
>>> a["b"]
0
>>> a["c"]
0
>>> a[0]
0
>>> a[1]
0
>>> a[2]
0
>>> a[1]
0
</code> </pre>

<h1> str </h1>

<p> Default for any key creates a dictionary of empty strings </p>

<pre> <code class="py">>>> a = defaultdict(str)
>>> a[0]
''
>>> a[1]
''
>>> a['some']
''
>>> a['what']
''
</code> </pre>

<h1> dict </h1>

<p> Dictionary whose default value is Dictionary </p>

<pre> <code class="py">>>> a = defaultdict(dict)
>>> a[0]
{}
>>> a['some']
{}
</code> </pre>

<h1> nested </h1>

<p> Defaultdict whose default value is defaultdict </p>

<pre> <code class="py">>>> a = defaultdict(lambda: defaultdict(int))
>>> a[0]
defaultdict(<class 'int'>, {})
>>> a[0][0]
0
>>> a["a"]["b"]
0
</code> </pre>

Original by Github issue

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

チャットメンバー募集

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

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

Twitter

https://twitter.com/YumaInaura

公開日時

2019-04-15

Discussion