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?
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'
As to whether this is a best practice in Python is up to debate:
hash = {}
hash['element1', 'sub1', 'subsub1'] = 'value'
if ('element1', 'sub1', 'subsub1') in hash:
print "found value"
But, it certainly works and is very elegant, if it works for you.
The major drawback is that you don't have intermediate access. You can't do:
if ('element1', 'sub1') in hash:
print "found value"
from collections import defaultdict
tree = lambda: defaultdict(tree)
t = tree()
t[1][2][3] = 4
t[1][3][3] = 5
t[1][2]['test'] = 6
from wikipedia Autovivification
I don't know if I'll get any agreement, but this is how I typically declare dictionaries of dictionaries:
someObj = {
'element1': {
'sub1': {
'subsub1': 'value1'
}
}
}
As for checking for the presence of an element, I agree with this approach:
try:
someObj['element1']['sub1']['subsub1']
except KeyError:
print('no value found')
else:
print('found value')
精彩评论