python nesting dictionary: OrderedDict from collections

空扰寡人 提交于 2019-12-05 15:59:46

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

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