Convert nested Python dict to object?

后端 未结 30 1979
时光取名叫无心
时光取名叫无心 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 10:19

    Taking what I feel are the best aspects of the previous examples, here's what I came up with:

    class Struct:
      '''The recursive class for building and representing objects with.'''
      def __init__(self, obj):
        for k, v in obj.iteritems():
          if isinstance(v, dict):
            setattr(self, k, Struct(v))
          else:
            setattr(self, k, v)
      def __getitem__(self, val):
        return self.__dict__[val]
      def __repr__(self):
        return '{%s}' % str(', '.join('%s : %s' % (k, repr(v)) for
          (k, v) in self.__dict__.iteritems()))
    

提交回复
热议问题