gpt4 book ai didi

python - 递归点字典

转载 作者:太空狗 更新时间:2023-10-29 21:29:36 26 4
gpt4 key购买 nike

我有一个实用程序类,它使 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'>

最佳答案

我没有看到您在构造函数中复制值的位置。因此,这里 DotDict 总是空的。当我添加键分配时,它起作用了:

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__

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


dct = {'scalar_value':1, 'nested_dict':{'value':2, 'nested_nested': {'x': 21}}}
dct = DotDict(dct)

print dct.nested_dict.nested_nested.x

它看起来有点危险且容易出错,更不用说给其他开发人员带来无数惊喜的来源了,但它似乎在起作用。

关于python - 递归点字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13520421/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com