Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

SOLVED: Set Python dict items recursively

Achilles Gasper Rasquinha:

I'd like to achieve the following:


foodict['foo.bar.baz'] = 'foo'
{
'foo': {
'bar': {
'baz': 'foo'
}
}
}
}

Creating keys recursively. I'm guessing the solution is simple but I'm too exhausted to figure out one.

After scratching my head for a while, I've come up with this:


class Config(dict):
def __init__(self, *args, **kwargs):
self.super = super(Config, self)
self.update(*args, **kwargs)

def __setitem__(self, keys, value):
keys = keys.split('.')
keys.reverse()

config = Config()

for i, k in enumerate(keys):
if i == 0:
config = Config(**{ k: value })
else:
config = Config(**{ k: config })

self.super.update(config)



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE


This post first appeared on Stack Solved, please read the originial post: here

Share the post

SOLVED: Set Python dict items recursively

×

Subscribe to Stack Solved

Get updates delivered right to your inbox!

Thank you for your subscription

×