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

Example of using defaultdict to prevent KeyError in # python's nested dictionary (#ruby comparison)

Last updated at Posted at 2019-04-15

example

  • Nesting and using defaultdict in layers
  • I can not get angry if I write a nonexistent key like d["x"]["y"]["z"]
  • Maybe a good girl may not be imitating
 >>> 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 
 

If you write in ruby

It was such a feeling. This is also a good girl.

 [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

How to use Python defaultdict-Qiita

Original by Github issue

チャットメンバー募集

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

Twitter

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