easydict库的用法以及改进型Easydict

本文深入探讨了Python中EasyDict库的使用方法,包括如何利用EasyDict简化字典操作,实现属性式的字典访问,以及EasyDict的递归特性。同时,文章还介绍了EasyDict的改进版,提供更强大的功能和灵活性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

(1)、在python中使用字典可以很方便的查看属性,但是字典遍历的方法不是那么方便,因此python提供了快速遍历字典的方法。

dict1 = {'num1':1,'num2':2}
print(dict1['num1'])
#以上为普通的字典的遍历方法,这种遍历在应用的时候不是很方便,查找属性必须按照列表的方法进行查找
from easydict import EasyDict as edict
dict1 = {'num1':1,'num2':2}
dict2 = edict(dict1)
#dict2就可以按照方式dict2.num1进行访问

(2)以下用法:

from easydict import EasyDict as edict

#注意,这里的mn和cfg的值永远都是一样的!!!!!!!!!
#不管用哪个的值增加,另外一个都会变!!!!!!
mn = edict()
cfg = mn


mn.TRAIN = edict()
mn.TRAIN.LEARNING_RATE = 0.001
mn.TRAIN.MOMENTUM = 0.9
mn.TRAIN.GAMMA = 0.1
mn.TRAIN.STEPSIZE = 50000
mn.TRAIN.DISPLAY = 10
mn.IS_MULTISCALE = False

print(mn)
print(cfg)
print(cfg.TRAIN)
print(cfg.TRAIN.DISPLAY)
print(mn.TRAIN.MOMENTUM)

(3)改进型Easydict

class EasyDict(dict):
    """
    Get attributes

    >>> d = EasyDict({'foo':3})
    >>> d['foo']
    3
    >>> d.foo
    3
    >>> d.bar
    Traceback (most recent call last):
    ...
    AttributeError: 'EasyDict' object has no attribute 'bar'

    Works recursively

    >>> d = EasyDict({'foo':3, 'bar':{'x':1, 'y':2}})
    >>> isinstance(d.bar, dict)
    True
    >>> d.bar.x
    1

    Bullet-proof

    >>> EasyDict({})
    {}
    >>> EasyDict(d={})
    {}
    >>> EasyDict(None)
    {}
    >>> d = {'a': 1}
    >>> EasyDict(**d)
    {'a': 1}

    Set attributes

    >>> d = EasyDict()
    >>> d.foo = 3
    >>> d.foo
    3
    >>> d.bar = {'prop': 'value'}
    >>> d.bar.prop
    'value'
    >>> d
    {'foo': 3, 'bar': {'prop': 'value'}}
    >>> d.bar.prop = 'newer'
    >>> d.bar.prop
    'newer'


    Values extraction

    >>> d = EasyDict({'foo':0, 'bar':[{'x':1, 'y':2}, {'x':3, 'y':4}]})
    >>> isinstance(d.bar, list)
    True
    >>> from operator import attrgetter
    >>> map(attrgetter('x'), d.bar)
    [1, 3]
    >>> map(attrgetter('y'), d.bar)
    [2, 4]
    >>> d = EasyDict()
    >>> d.keys()
    []
    >>> d = EasyDict(foo=3, bar=dict(x=1, y=2))
    >>> d.foo
    3
    >>> d.bar.x
    1

    Still like a dict though

    >>> o = EasyDict({'clean':True})
    >>> o.items()
    [('clean', True)]

    And like a class

    >>> class Flower(EasyDict):
    ...     power = 1
    ...
    >>> f = Flower()
    >>> f.power
    1
    >>> f = Flower({'height': 12})
    >>> f.height
    12
    >>> f['power']
    1
    >>> sorted(f.keys())
    ['height', 'power']
    """
    def __init__(self, d=None, **kwargs):
        if d is None:
            d = {}
        if kwargs:
            d.update(**kwargs)
        for k, v in d.items():
            setattr(self, k, v)
        # Class attributes
        for k in self.__class__.__dict__.keys():
            if not (k.startswith('__') and k.endswith('__')):
                setattr(self, k, getattr(self, k))

    def __setattr__(self, name, value):
        if isinstance(value, (list, tuple)):
            def get_EasyDict_list(value):
                return [EasyDict(x) if isinstance(x, dict) else x if not isinstance(x, (list, tuple)) else get_EasyDict_list(x) for x in value]
            value = get_EasyDict_list(value)
        else:
            value = EasyDict(value) if isinstance(value, dict) else value
        super(EasyDict, self).__setattr__(name, value)
        self[name] = value

    def __getattr__(self, name):
        """
        如果 key 不存在返回 None
        """
        try:
            return super(EasyDict, self).__getattr__(name)
        except AttributeError:
            try:
                return self[name]
            except KeyError:
                key = name or ""
                if key.startswith('__') and key.endswith('__'):
                    raise AttributeError
                return None

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值