简体   繁体   中英

python nesting dictionary: OrderedDict from collections

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM