2
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 の defaultdict を利用して KeyError を防ぎたい

Last updated at Posted at 2019-04-15

import

>>> from collections import defaultdict

int

どんなキーでもデフォルト値が0のディクショナリを作る

>>> 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

str

どんなキーでもデフォルトが空白文字列の辞書を作る

>>> a = defaultdict(str)
>>> a[0]
''
>>> a[1]
''
>>> a['some']
''
>>> a['what']
''

dict

デフォルト値がディクショナリのディクショナリ

>>> a = defaultdict(dict)
>>> a[0]
{}
>>> a['some']
{}

nested

デフォルト値が defaultdict の defaultdict

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

Original by Github issue

チャットメンバー募集

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

Twitter

2
0
0

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
2
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?