属性の取得と設定に関して、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__
orでこのようなことができることを望んでいましたが、うまくいくものは__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'>