开发者

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

This question already has answers here: What is the best way to implement nested dictionaries? 开发者_如何学编程 (21 answers) Closed 7 years ago.

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')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜