python nesting dictionary: OrderedDict from collections

那年仲夏 提交于 2019-12-10 06:40:47

问题


how to nest a OrderedDict?

i tried:

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

but this shows error.

i tried also:

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

this also shows error.

i tried:

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

this works fine.

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

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.

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


回答1:


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])



回答2:


You can define your own custom subclass of OrderedDict, handle the __missing__ method to support infinite nesting.

from collections import OrderedDict

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

Demo:

>>> 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']



回答3:


class OrderedDefaultDict(OrderedDict):
    def __init__(self, default_factory=None, *args, **kwargs):
        super(OrderedDefaultDict, self).__init__(*args, **kwargs)
        self.default_factory = default_factory
    def __missing__(self, key):
        if self.default_factory is None:
            raise KeyError(key)
        val = self[key] = self.default_factory()
        return val

It's simple enough to subclass OrderedDict with defaultdict-like behavior. You can then use an OrderedDefaultDict as follows:

table = OrderedDefaultDict(OrderedDict)
table['a']['b'] = 3


来源:https://stackoverflow.com/questions/18809482/python-nesting-dictionary-ordereddict-from-collections

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!