easydict能够让我们使用.操作符,就像访问属性attribute那样访问字典dictionary的值。它不是内置模块,可以通过pip进行安装
pip install easydict
来看看代码示例
(base) PS C:\Windows\system32> ipythonPython 3.7.6 (default, Jan 8 2020, 20:23:39) [MSC v.1916 64 bit (AMD64)]Type 'copyright', 'credits' or 'license' for more informationIPython 7.13.0 -- An enhanced Interactive Python. Type '?' for help.In [1]: from easydict import EasyDict as edictIn [2]: aDict = {'p':'python', 'j':'java', 's':'swift', 'r':'rust'} ...:In [3]: edict(aDict)Out[3]: {'p': 'python', 'j': 'java', 's': 'swift', 'r': 'rust'}In [4]: e = edict(aDict)In [5]: e.pOut[5]: 'python'In [6]: e.jOut[6]: 'java'In [7]: e.sOut[7]: 'swift'In [8]: e.rOut[8]: 'rust'In [9]: e['r']Out[9]: 'rust'In [10]:
示例中,我们将字典aDict传递给EasyDict得到对象e,然后就可以通过e.加上字典中的key值来访问对应的value值了。这个过程是递归的,看下面的例子
In [1]: from easydict import EasyDict as edictIn [2]: aDict = {'id':1, 'data':{'name':'xugaoxiang', 'sex':'male'}}In [3]: e = edict(aDict)In [4]: e.idOut[4]: 1In [5]: e.data.nameOut[5]: 'xugaoxiang'In [6]: e.data.sexOut[6]: 'male'In [7]:
同样的,我们也可以通过.操作符来给属性赋值
In [1]: from easydict import EasyDict as edictIn [2]: d = edict()In [3]: d.name = 'xugaoxiang'In [4]: d.sex = 'male'In [5]: dOut[5]: {'name': 'xugaoxiang', 'sex': 'male'}
联系客服