欢迎访问我的网站,希望内容对您有用,感兴趣的可以加入免费知识星球。

Python实用模块(二十二)easydict

实用模块 迷途小书童 4年前 (2020-10-04) 2704次浏览 0个评论

软硬件环境

  • windows 10 64bit
  • anaconda3 with python 3.7
  • easydict 1.9

视频看这里

此处是 youtube 的播放链接,需要科学上网。喜欢我的视频,请记得订阅我的频道,打开旁边的小铃铛,点赞并分享,感谢您的支持。

前言

easydict 能够让我们使用 . 操作符,就像访问属性 attribute 那样访问字典 dictionary 的值。它不是内置模块,可以通过 pip 进行安装

pip install easydict

示例

来看看代码示例

(base) PS C:\Windows\system32> ipython
Python 3.7.6 (default, Jan  8 2020, 20:23:39) [MSC v.1916 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 7.13.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: from easydict import EasyDict as edict

In [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.p
Out[5]: 'python'

In [6]: e.j
Out[6]: 'java'

In [7]: e.s
Out[7]: 'swift'

In [8]: e.r
Out[8]: 'rust'

In [9]: e["r"]
Out[9]: 'rust'

In [10]:

示例中,我们将字典 aDict 传递给 EasyDict 得到对象 e,然后就可以通过 e. 加上字典中的 key 值来访问对应的 value 值了。这个过程是递归的,看下面的例子

In [1]: from easydict import EasyDict as edict

In [2]: aDict = {"id":1, "data":{"name":"xugaoxiang", "sex":"male"}}

In [3]: e = edict(aDict)

In [4]: e.id
Out[4]: 1

In [5]: e.data.name
Out[5]: 'xugaoxiang'

In [6]: e.data.sex
Out[6]: 'male'

In [7]:  

同样的,我们也可以通过 . 操作符来给属性赋值

In [1]: from easydict import EasyDict as edict

In [2]: d = edict()

In [3]: d.name = "xugaoxiang"

In [4]: d.sex = "male"

In [5]: d
Out[5]: {'name': 'xugaoxiang', 'sex': 'male'}

参考资料

喜欢 (1)

您必须 登录 才能发表评论!