在Python中初始化字典的最好方法是什么?
很多时候,在 Perl 中,我会做这样的事情:
$myhash{foo}{bar}{baz} = 1
我如何将其转换为 Python? 到目前为止我已经:
if not 'foo' in myhash:
myhash['foo'] = {}
if not 'bar' in myhash['foo']:
myhash['foo']['bar'] = {}
myhash['foo']['bar']['baz'] = 1
有更好的方法吗?
A lot of times in Perl, I'll do something like this:
$myhash{foo}{bar}{baz} = 1
How would I translate this to Python? So far I have:
if not 'foo' in myhash:
myhash['foo'] = {}
if not 'bar' in myhash['foo']:
myhash['foo']['bar'] = {}
myhash['foo']['bar']['baz'] = 1
Is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您需要的嵌套数量是固定的,
collections.defaultdict
就非常适合。例如嵌套两层:
如果你想进入另一个层次的嵌套,你需要做类似的事情:
编辑:MizardX 指出我们可以通过一个简单的函数获得完整的通用性:
现在我们可以这样做:
If the amount of nesting you need is fixed,
collections.defaultdict
is wonderful.e.g. nesting two deep:
If you want to go another level of nesting, you'll need to do something like:
edit: MizardX points out that we can get full genericity with a simple function:
Now we can do:
测试:
输出:
Testing:
Output:
有什么理由让它成为字典中的字典吗? 如果该特定结构没有令人信服的理由,您可以简单地使用元组索引字典:
如果使用元组键初始化字典,则需要括号,但在使用 [] 设置/获取值时可以省略它们:
Is there a reason it needs to be a dict of dicts? If there's no compelling reason for that particular structure, you could simply index the dict with a tuple:
The parentheses are required if you initialize the dict with a tuple key, but you can omit them when setting/getting values using []:
我想直译应该是:
打电话:
给你 1。
不过,这对我来说有点恶心。
(不过,我不是 Perl 人,所以我猜测你的 Perl 做了什么)
I guess the literal translation would be:
Calling:
gives you 1.
That looks a little gross to me, though.
(I'm no perl guy, though, so I'm guessing at what your perl does)