Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 362
jbb Avatar asked Jun 26 '10 03:06

jbb


1 Answers

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'
like image 131
Alex Martelli Avatar answered Oct 22 '22 16:10

Alex Martelli