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

大城市里の小女人 提交于 2019-11-28 09:11:16

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')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!