python嵌套字典:集合中的OrderedDict

python nesting dictionary: OrderedDict from collections(python嵌套字典:集合中的OrderedDict)

本文介绍了python嵌套字典:集合中的OrderedDict的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何嵌套 OrderedDict?

how to nest a 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'

这很好用.

在我的编码中,我必须这样使用:

in my coding i had to use like this:

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

效果很好.但是有没有其他方法.当我读到 python 时会自动管理它的数据结构.

which works fine. but is there any other method. as i read python manages its data structure automatically.

无论如何都可以声明一个字典以及它的嵌套数量以及它在一行中嵌套的数据结构是什么.

is there anyway to declare a dictionary along with how much nesting it'll be and what will be the data-structures of its nests in one line.

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

using an extra loop just to declare a dictionary feels like i'm missing something in python.

推荐答案

如果你真的想在一行中完成,那么这行得通

If you really want to do it in one line, then this would work

table = collections.OrderedDict([(lhs, collections.OrderedDict(zip(terminal, [0] * len(terminal)))) for lhs in left])

你最好(特别是如果终端有很多成员)这样做

You would be best off (especially if terminal has a lot of members) doing

zipped = zip(terminal, [0] * len(terminal))
table = collections.OrderedDict([(lhs, collections.OrderedDict(zipped)) for lhs in left])

这篇关于python嵌套字典:集合中的OrderedDict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:python嵌套字典:集合中的OrderedDict

基础教程推荐