小编Ach*_*nha的帖子

给定复合键'foo.bar.baz'时,递归设置Python dict项

我想实现以下目标:

foodict['foo.bar.baz'] = 'foo'
{
   'foo': {
      'bar': {
            'baz': 'foo'
         }
       }
   }
}
Run Code Online (Sandbox Code Playgroud)

...递归创建密钥.

抓了一会儿之后,我想出了这个:

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)
Run Code Online (Sandbox Code Playgroud)

python recursion dictionary

10
推荐指数
1
解决办法
534
查看次数

标签 统计

dictionary ×1

python ×1

recursion ×1