如何通过点“。”访问Python词典成员?
例如,mydict['val']我想写而不是写mydict.val。
mydict['val']
mydict.val
我也想以这种方式访问嵌套的字典。例如
mydict.mydict2.val
将指
mydict = { 'mydict2': { 'val': ... } }
你可以使用我刚刚制作的此类来做。通过此类,你可以Map像其他字典(包括json序列化)一样使用该对象,也可以使用点符号。希望对你有所帮助:
Map
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'