How to assign hash[‘a’][‘b’]= ‘c’ if hash[‘a’] doesn’t exist?

The easiest way is to construct your Hash with a block argument: hash = Hash.new { |h, k| h[k] = { } } hash[‘a’][‘b’] = 1 hash[‘a’][‘c’] = 1 hash[‘b’][‘c’] = 1 puts hash.inspect # “{“a”=>{“b”=>1, “c”=>1}, “b”=>{“c”=>1}}” This form for new creates a new empty Hash as the default value. You don’t want this: … Read more

What’s the best way to initialize a dict of dicts in Python? [duplicate]

If the amount of nesting you need is fixed, collections.defaultdict is wonderful. e.g. nesting two deep: myhash = collections.defaultdict(dict) myhash[1][2] = 3 myhash[1][3] = 13 myhash[2][4] = 9 If you want to go another level of nesting, you’ll need to do something like: myhash = collections.defaultdict(lambda : collections.defaultdict(dict)) myhash[1][2][3] = 4 myhash[1][3][3] = 5 myhash[1][2][‘test’] … Read more