递归点点狄

2024-04-28 19:58:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个实用程序类,它使Python字典在获取和设置属性方面有点像JavaScript对象。

class DotDict(dict):
    """
    a dictionary that supports dot notation 
    as well as dictionary access notation 
    usage: d = DotDict() or d = DotDict({'val1':'first'})
    set attributes: d.val2 = 'second' or d['val2'] = 'second'
    get attributes: d.val2 or d['val2']
    """
    __getattr__ = dict.__getitem__
    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__

我希望它也能将嵌套字典转换为DotDict()实例。我本来希望能用__init____new__来做这样的事情,但我没有想出任何有效的方法:

def __init__(self, dct):
    for key in dct.keys():
        if hasattr(dct[key], 'keys'):
            dct[key] = DotDict(dct[key])

如何递归地将嵌套字典转换为DotDict()实例?

>>> dct = {'scalar_value':1, 'nested_dict':{'value':2}}
>>> dct = DotDict(dct)

>>> print dct
{'scalar_value': 1, 'nested_dict': {'value': 2}}

>>> print type(dct)
<class '__main__.DotDict'>

>>> print type(dct['nested_dict'])
<type 'dict'>

Tags: orkeydictionary字典valueastypedict