1
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 の ネストされた辞書で KeyError を起こさないように defaultdict を利用する例 ( #ruby 比較 )

Last updated at Posted at 2019-04-15

example

  • defaultdict を何層にもネストして使ってみる
  • d["x"]["y"]["z"] のように存在しないキーを書いても怒られない
  • もしかしたら良い子は真似しちゃダメかもしれない
>>> 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

ruby で書くなら

こんな感じだったかな。こちらも良い子はマネし‥。

[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

ref

Python defaultdict の使い方 - Qiita

Original by Github issue

チャットメンバー募集

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

Twitter

1
0
2

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