python嵌套字典: OrderedDict from collections

标签 python dictionary nested

如何嵌套 OrderedDict?

我试过:

table=collections.OrderedDict()
table['E']['a']='abc'

但这显示错误。

我也试过:

table=collections.OrderedDict(OrderedDict())
table['E']['a']='abc'

这也显示错误。

我试过:

table=collections.OrderedDict()
table['E']=collections.OrderedDict()
table['E']['a']='abc'

这很好用。

在我的编码中我不得不这样使用:

table=collections.OrderedDict()
for lhs in left:
    table[lhs]=collections.OrderedDict()
    for val in terminal:
        table[lhs][val]=0

效果很好。但有没有其他方法。正如我所读,python 自动管理其数据结构。

无论如何要声明一个字典以及它将有多少嵌套以及它在一行中的嵌套的数据结构是什么。

使用一个额外的循环来声明一个字典感觉就像我在 python 中遗漏了一些东西。

最佳答案

您可以自定义OrderedDict的子类,处理__missing__方法以支持无限嵌套。

from collections import OrderedDict

class MyDict(OrderedDict):
    def __missing__(self, key):
        val = self[key] = MyDict()
        return val

演示:

>>> d = MyDict()
>>> d['b']['c']['e'] = 100
>>> d['a']['c']['e'] = 100
>>> d.keys()
['b', 'a']
>>> d['a']['d']['e'] = 100
>>> d['a'].keys()
['c', 'd']

关于python嵌套字典: OrderedDict from collections,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18809482/

相关文章:

python - 使用多个 'for' 循环解码嵌套的 JSON

python - 文件描述符使用什么变量名?

python - 为什么 return 最终给出空字典?

python - 默认 xampp-linux 安装中缺少 config_vars.mk

c++学习 map 条目的顺序

python - 打印 Python 字典中的所有唯一值

nested - 在另一个模板中嵌套闭包模板

java - 在Java中嵌套类并在静态main中引用它们

python - Tf-Idf vectorizer 从行而不是单词分析向量

python - 当 slider 更新 matplotlib 时绘图不刷新