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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With