如何使用点“.”来访问字典的成员?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (56)

如何使Python字典成员通过点“?”访问?

例如,代替写作mydict['val'],我想写mydict.val...

另外,我也想以这种方式访问嵌套的DECTS。例如

mydict.mydict2.val 

会提到

mydict = { 'mydict2': { 'val': ... } }
提问于
用户回答回答于

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]

用法示例:

m = Map({'first_name': 'Eduardo'}, last_name='Pool', age=24, sports=['Soccer'])
# Add new key
m.new_key = 'Hello world!'
# Or
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']
用户回答回答于

我一直把这个放在一个util文件里。你也可以在自己的类中使用它作为混合。

>>> class dotdict(dict):
...     """dot.notation access to dictionary attributes"""
...     __getattr__ = dict.get
...     __setattr__ = dict.__setitem__
...     __delattr__ = dict.__delitem__
... 
>>> mydict = {'val':'it works'}
>>> nested_dict = {'val':'nested works too'}
>>> mydict = dotdict(mydict)
>>> mydict.val
'it works'
>>> mydict.nested = dotdict(nested_dict)
>>> mydict.nested.val
'nested works too'

扫码关注云+社区