Convert nested Python dict to object?

后端 未结 30 1928
时光取名叫无心
时光取名叫无心 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!

    0 讨论(0)
  • 2020-11-22 09:59

    If your dict is coming from json.loads(), you can turn it into an object instead (rather than a dict) in one line:

    import json
    from collections import namedtuple
    
    json.loads(data, object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))
    

    See also How to convert JSON data into a Python object.

    0 讨论(0)
  • 2020-11-22 09:59
    from mock import Mock
    d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
    my_data = Mock(**d)
    
    # We got
    # my_data.a == 1
    
    0 讨论(0)
  • 2020-11-22 09:59

    What about just assigning your dict to the __dict__ of an empty object?

    class Object:
        """If your dict is "flat", this is a simple way to create an object from a dict
    
        >>> obj = Object()
        >>> obj.__dict__ = d
        >>> d.a
        1
        """
        pass
    

    Of course this fails on your nested dict example unless you walk the dict recursively:

    # For a nested dict, you need to recursively update __dict__
    def dict2obj(d):
        """Convert a dict to an object
    
        >>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
        >>> obj = dict2obj(d)
        >>> obj.b.c
        2
        >>> obj.d
        ["hi", {'foo': "bar"}]
        """
        try:
            d = dict(d)
        except (TypeError, ValueError):
            return d
        obj = Object()
        for k, v in d.iteritems():
            obj.__dict__[k] = dict2obj(v)
        return obj
    

    And your example list element was probably meant to be a Mapping, a list of (key, value) pairs like this:

    >>> d = {'a': 1, 'b': {'c': 2}, 'd': [("hi", {'foo': "bar"})]}
    >>> obj = dict2obj(d)
    >>> obj.d.hi.foo
    "bar"
    
    0 讨论(0)
  • 2020-11-22 10:00
    x = type('new_dict', (object,), d)
    

    then add recursion to this and you're done.

    edit this is how I'd implement it:

    >>> d
    {'a': 1, 'b': {'c': 2}, 'd': ['hi', {'foo': 'bar'}]}
    >>> def obj_dic(d):
        top = type('new', (object,), d)
        seqs = tuple, list, set, frozenset
        for i, j in d.items():
            if isinstance(j, dict):
                setattr(top, i, obj_dic(j))
            elif isinstance(j, seqs):
                setattr(top, i, 
                    type(j)(obj_dic(sj) if isinstance(sj, dict) else sj for sj in j))
            else:
                setattr(top, i, j)
        return top
    
    >>> x = obj_dic(d)
    >>> x.a
    1
    >>> x.b.c
    2
    >>> x.d[1].foo
    'bar'
    
    0 讨论(0)
  • 2020-11-22 10:01

    I ended up trying BOTH the AttrDict and the Bunch libraries and found them to be way too slow for my uses. After a friend and I looked into it, we found that the main method for writing these libraries results in the library aggressively recursing through a nested object and making copies of the dictionary object throughout. With this in mind, we made two key changes. 1) We made attributes lazy-loaded 2) instead of creating copies of a dictionary object, we create copies of a light-weight proxy object. This is the final implementation. The performance increase of using this code is incredible. When using AttrDict or Bunch, these two libraries alone consumed 1/2 and 1/3 respectively of my request time(what!?). This code reduced that time to almost nothing(somewhere in the range of 0.5ms). This of course depends on your needs, but if you are using this functionality quite a bit in your code, definitely go with something simple like this.

    class DictProxy(object):
        def __init__(self, obj):
            self.obj = obj
    
        def __getitem__(self, key):
            return wrap(self.obj[key])
    
        def __getattr__(self, key):
            try:
                return wrap(getattr(self.obj, key))
            except AttributeError:
                try:
                    return self[key]
                except KeyError:
                    raise AttributeError(key)
    
        # you probably also want to proxy important list properties along like
        # items(), iteritems() and __len__
    
    class ListProxy(object):
        def __init__(self, obj):
            self.obj = obj
    
        def __getitem__(self, key):
            return wrap(self.obj[key])
    
        # you probably also want to proxy important list properties along like
        # __iter__ and __len__
    
    def wrap(value):
        if isinstance(value, dict):
            return DictProxy(value)
        if isinstance(value, (tuple, list)):
            return ListProxy(value)
        return value
    

    See the original implementation here by https://stackoverflow.com/users/704327/michael-merickel.

    The other thing to note, is that this implementation is pretty simple and doesn't implement all of the methods you might need. You'll need to write those as required on the DictProxy or ListProxy objects.

    0 讨论(0)
提交回复
热议问题