Convert nested Python dict to object?

后端 未结 30 2699
时光取名叫无心
时光取名叫无心 2020-11-22 09:28

I\'m searching for an elegant way to get data using attribute access on a dict with some nested dicts and lists (i.e. javascript-style object syntax).

For example:

30条回答
  •  礼貌的吻别
    2020-11-22 09:58

    Wanted to upload my version of this little paradigm.

    class Struct(dict):
      def __init__(self,data):
        for key, value in data.items():
          if isinstance(value, dict):
            setattr(self, key, Struct(value))
          else:   
            setattr(self, key, type(value).__init__(value))
    
          dict.__init__(self,data)
    

    It preserves the attributes for the type that's imported into the class. My only concern would be overwriting methods from within the dictionary your parsing. But otherwise seems solid!

提交回复
热议问题