Accessing dict keys like an attribute?

前端 未结 27 2120
南笙
南笙 2020-11-22 04:22

I find it more convenient to access dict keys as obj.foo instead of obj[\'foo\'], so I wrote this snippet:

class AttributeDict(dict         


        
27条回答
  •  礼貌的吻别
    2020-11-22 05:00

    You can do it using this class I just made. With this class you can use the Map object like another dictionary(including json serialization) or with the dot notation. I hope help you:

    class Map(dict):
        """
        Example:
        m = Map({'first_name': 'Eduardo'}, last_name='Pool', age=24, sports=['Soccer'])
        """
        def __init__(self, *args, **kwargs):
            super(Map, self).__init__(*args, **kwargs)
            for arg in args:
                if isinstance(arg, dict):
                    for k, v in arg.iteritems():
                        self[k] = v
    
            if kwargs:
                for k, v in kwargs.iteritems():
                    self[k] = v
    
        def __getattr__(self, attr):
            return self.get(attr)
    
        def __setattr__(self, key, value):
            self.__setitem__(key, value)
    
        def __setitem__(self, key, value):
            super(Map, self).__setitem__(key, value)
            self.__dict__.update({key: value})
    
        def __delattr__(self, item):
            self.__delitem__(item)
    
        def __delitem__(self, key):
            super(Map, self).__delitem__(key)
            del self.__dict__[key]
    

    Usage examples:

    m = Map({'first_name': 'Eduardo'}, last_name='Pool', age=24, sports=['Soccer'])
    # Add new key
    m.new_key = 'Hello world!'
    print m.new_key
    print m['new_key']
    # Update values
    m.new_key = 'Yay!'
    # Or
    m['new_key'] = 'Yay!'
    # Delete key
    del m.new_key
    # Or
    del m['new_key']
    

提交回复
热议问题