python - 嵌套默认字典

标签 python python-2.7

为什么下面的方法有效

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

最佳答案

这里的问题是 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!

如果您只需要有限级别的嵌套,那么使用带有 tuple 键的普通旧 dict 通常是一种更容易使用的数据结构。这对于您问题中显示的 2-d 和 3-d 示例都适用。

但是,如果您需要任意级别的嵌套,则可以考虑所示的递归 defaultdict 示例 here .

关于python - 嵌套默认字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39725255/

相关文章:

python - 使用 pyMongo 获取 mongodb 中的复制延迟

python - 如果列表中的所有内容 == 某事

python - 如何访问这个没有 id 的 <div class> 内的文本?使用BeautifulSoup

python-2.7 - Python 中键为 "similar"的字典的总和

Python:如何为 XML 文档生成唯一标识符?

python - 将 fork 的 python 进程的输出重定向到管道

Python 自动运行程序,无需 shell 保持打开状态

python - 使用 Dask 从 postgresql 导入数据

python - django 删除管理站点中的模型 - 'bool' 对象不可调用

python - CPython - 编译 dails,PyDateTime_FromTimestamp 未声明?