嵌套默认字典

问题描述 投票:0回答:1

为什么下面的方法有效

x = defaultdict(dict)
for a,b,c in [('eg', 'ef', 'ee'), ('eg', 'eu', 'e4'), ('kk', 'nn', 'bb')]:
    x[a][b] = c

下面会抛出错误?

x = defaultdict(dict)
for a,b,c,d in [('eg', 'ef', 'ee', 'gg'), ('eg', 'eu', 'e4', 'hh'),
                ('kk', 'nn', 'bb', 'ff')]:
    x[a][b][c] = d
python
1个回答
2
投票

这里的问题是

defaultdict
接受一个可调用的,它被用作工厂来在键丢失时生成值。一旦你理解了这一点,行为就很清楚了:

x = defaultdict(dict)
x                    # it's a default dict
x['a']               # it's just a dict()
x['a']['b'] = 'c'    # it's just setting the 'b' item in the dict x['a']
x['a']['b']['z']     # oops, error, because x['a']['b'] is not a dict!

如果您只需要有限级别的嵌套,则使用带有

dict
键的普通老式
tuple
通常是一种更容易使用的数据结构。这对于您问题中显示的 2-d 和 3-d 示例都适用。

但是,如果您需要任意级别的嵌套,则可以考虑

defaultdict
所示的递归示例此处

© www.soinside.com 2019 - 2024. All rights reserved.