jbb*_*jbb 13 python dictionary autovivification
谷歌和在线文档都没有提供我的查询的很多见解,所以我想我会在这里问社区.
在Perl中,您可以轻松设置哈希哈希哈希值并测试最终密钥,如下所示:
my $hash = {};
$hash{"element1"}{"sub1"}{"subsub1"} = "value1";
if (exists($hash{"element1"}{"sub1"}{"subsub1"})) {
print "found value\n";
}
Run Code Online (Sandbox Code Playgroud)
什么是Python中的"最佳实践"等价物?
Ale*_*lli 16
最接近的等价物可能类似于以下内容:
import collections
def hasher():
return collections.defaultdict(hasher)
hash = hasher()
hash['element1']['sub1']['subsub1'] = 'value1'
if 'subsub1' in hash['element1']['sub1']:
print 'found value'
Run Code Online (Sandbox Code Playgroud)
至于这是否是Python中的最佳实践还有争议:
hash = {}
hash['element1', 'sub1', 'subsub1'] = 'value'
if ('element1', 'sub1', 'subsub1') in hash:
print "found value"
Run Code Online (Sandbox Code Playgroud)
但是,它肯定有效,并且非常优雅,如果它适合你.
主要缺点是您没有中间访问权限.你不能做的:
if ('element1', 'sub1') in hash:
print "found value"
Run Code Online (Sandbox Code Playgroud)