ネストされた Python 辞書をオブジェクトに変換するにはどうすればいいですか? 質問する

ネストされた Python 辞書をオブジェクトに変換するにはどうすればいいですか? 質問する

私は、ネストされた辞書とリスト (つまり、JavaScript スタイルのオブジェクト構文) を持つ辞書の属性アクセスを使用してデータを取得するエレガントな方法を探しています。

例えば:

>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}

次の方法でアクセスできるはずです:

>>> x = dict2obj(d)
>>> x.a
1
>>> x.b.c
2
>>> x.d[1].foo
bar

これは再帰なしでは不可能だと思いますが、辞書のオブジェクト スタイルを取得する良い方法は何でしょうか?

ベストアンサー1

更新: Python 2.6以降では、namedtupleニーズに合ったデータ構造:

>>> from collections import namedtuple
>>> MyStruct = namedtuple('MyStruct', 'a b d')
>>> s = MyStruct(a=1, b={'c': 2}, d=['hi'])
>>> s
MyStruct(a=1, b={'c': 2}, d=['hi'])
>>> s.a
1
>>> s.b
{'c': 2}
>>> s.c
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'MyStruct' object has no attribute 'c'
>>> s.d
['hi']

代替案(元の回答内容)は次のとおりです。

class Struct:
    def __init__(self, **entries):
        self.__dict__.update(entries)

次に、以下を使用できます。

>>> args = {'a': 1, 'b': 2}
>>> s = Struct(**args)
>>> s
<__main__.Struct instance at 0x01D6A738>
>>> s.a
1
>>> s.b
2

おすすめ記事