如何使用点“."访问字典成员? [英] How to use a dot "." to access members of dictionary?

查看:28
本文介绍了如何使用点“."访问字典成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过点."访问 Python 字典成员?

How do I make Python dictionary members accessible via a dot "."?

例如,我想写 mydict.val 而不是写 mydict['val'].

For example, instead of writing mydict['val'], I'd like to write mydict.val.

我也想以这种方式访问​​嵌套的字典.例如

Also I'd like to access nested dicts this way. For example

mydict.mydict2.val 

会参考

mydict = { 'mydict2': { 'val': ... } }

推荐答案

你可以使用我刚刚制作的这个类来完成.使用这个类,您可以像使用另一个字典(包括 json 序列化)或点符号一样使用 Map 对象.希望能帮到你:

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 to 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]

使用示例:

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']

这篇关于如何使用点“."访问字典成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆