python - 在一个 dict 的 dict 中,你如何模拟 Perl 的自动激活行为?

标签 python dictionary autovivification

<分区>

Google 和在线文档都没有对我的查询提供太多见解,所以我想我会在这里问社区。

在 Perl 中,您可以轻松地设置一个哈希的哈希并像这样测试最终的 key :

my $hash = {};
$hash{"element1"}{"sub1"}{"subsub1"} = "value1";
if (exists($hash{"element1"}{"sub1"}{"subsub1"})) {
   print "found value\n";
}

Python 中的“最佳实践”是什么?

最佳答案

最接近的等价物可能如下所示:

import collections

def hasher():
  return collections.defaultdict(hasher)

hash = hasher()
hash['element1']['sub1']['subsub1'] = 'value1'
if 'subsub1' in hash['element1']['sub1']:
  print 'found value'

关于python - 在一个 dict 的 dict 中,你如何模拟 Perl 的自动激活行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3122566/

相关文章:

java - 什么将在 Java 中存储键值列表或在 Java 中存储 C# IDictionary 的替代品?

c++ - 在 C++ 中显示字符串、vector<int> 映射

ruby - 如果哈希 ['a' ] 不存在,如何分配哈希 ['b' ] 'c' ]= ['a'?

python - Bokeh 中可能的更新导致了一个奇怪的生成器错误

python - 如何将 Gtk.Image 转换为 base64

python - 使用lora接收树莓派上的杂乱数据

c# - C#中唯一的字符串集

python - 如果我们使用索引矩阵,是否需要在 Theano 中使用 flatten 和 reshape?

调用子程序时的 perl 自动激活