在字典中的字典中,如何模拟 Perl 的自动激活行为?
谷歌和在线文档都没有对我的查询提供太多见解,所以我想我应该在这里询问社区。
在 Perl 中,您可以轻松设置哈希的哈希并测试最终密钥,如下所示:
my $hash = {};
$hash{"element1"}{"sub1"}{"subsub1"} = "value1";
if (exists($hash{"element1"}{"sub1"}{"subsub1"})) {
print "found value\n";
}
Python 中的“最佳实践”等效项是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
最接近的等效项可能如下所示:
The closest equivalent is probably something like the following:
至于这是否是 Python 中的最佳实践还有待争论:
但是,如果它适合您,它肯定有效并且非常优雅。
主要缺点是您没有中间访问权限。你不能做:
As to whether this is a best practice in Python is up to debate:
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:
来自 维基百科 Autovivification
from wikipedia Autovivification
我不知道我是否会得到任何同意,但这就是我通常声明字典的字典的方式:
至于检查元素是否存在,我同意这种方法:
I don't know if I'll get any agreement, but this is how I typically declare dictionaries of dictionaries:
As for checking for the presence of an element, I agree with this approach: