Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 259
RatDon Avatar asked Sep 15 '13 06:09

RatDon


2 Answers

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']
like image 59
Ashwini Chaudhary Avatar answered Nov 15 '22 10:11

Ashwini Chaudhary


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])
like image 37
sberry Avatar answered Nov 15 '22 11:11

sberry