python嵌套字典:OrderedDict从集合 [英] python nesting dictionary: OrderedDict from collections

查看:310
本文介绍了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从集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆