pythondictionaryautovivification

In a dict of dicts, how do you emulate Perl's auto-vivification behavior?


Both Google and the online docs are not delivering much insight on my query, so I thought I would ask the community here.

In Perl, you can easily setup a hash-of-a-hash-of-a-hash and test the final key like so:

my $hash = {};
$hash{"element1"}{"sub1"}{"subsub1"} = "value1";
if (exists($hash{"element1"}{"sub1"}{"subsub1"})) {
   print "found value\n";
}

What's the 'best-practice' equivalent in Python?


Solution

  • The closest equivalent is probably something like the following:

    import collections
    
    def hasher():
      return collections.defaultdict(hasher)
    
    hash = hasher()
    hash['element1']['sub1']['subsub1'] = 'value1'
    if 'subsub1' in hash['element1']['sub1']:
      print 'found value'