python 中的 easydict


 

寫在前面:當遇到一個陌生的python第三方庫時,可以去pypi這個主頁查看描述以迅速入門!
import time
 
dir(time)

  



easydict的作用:可以使得以屬性的方式去訪問字典的值!
>>> from easydict import EasyDict as edict
 
>>> d = edict({'foo':3, 'bar':{'x':1, 'y':2}})
 
>>> d.foo
 
3
 
>>> d.bar.x
 
1
 
 
 
>>> d = edict(foo=3)
 
>>> d.foo
 
3

 解析json目錄時很有

>>> from easydict import EasyDict as edict
 
>>> from simplejson import loads
 
>>> j = """{
 
"Buffer": 12,
 
"List1": [
 
{"type" : "point", "coordinates" : [100.1,54.9] },
 
{"type" : "point", "coordinates" : [109.4,65.1] },
 
{"type" : "point", "coordinates" : [115.2,80.2] },
 
{"type" : "point", "coordinates" : [150.9,97.8] }
 
]
 
}"""
 
>>> d = edict(loads(j))
 
>>> d.Buffer
 
12
 
>>> d.List1[0].coordinates[1]
 
54.9

  

 

也可以這樣用
 
>>> d = EasyDict()
 
>>> d.foo = 3
 
>>> d.foo
 
3
 
>>> d = EasyDict(log=False)
 
>>> d.debug = True
 
>>> d.items()
 
[('debug', True), ('log', False)]

 
>>> class Flower(EasyDict):
 
... power = 1
 
...
 
>>> f = Flower({'height': 12})
 
>>> f.power
 
1
 
>>> f['power']
 
1

  



EasyDict可以讓你像訪問屬性一樣訪問dict里的變量。

1. 問題

d = {'foo':3, 'bar':{'x':1, 'y':2}}
print(d['foo']) # 如何想要訪問字典的元素需要這么寫
print(d['bar']['y']) # 如果想要繼續訪問字典中字典的元素需要使用二維數組
# print(d.foo) 這樣寫會出錯哦!

  



輸出:

3
2

但是感覺這樣太麻煩了,有沒有更簡單的方法使用字典了?

2. 解決方法
我們可以使用easydict模塊!

from easydict import EasyDict as edict
easy = edict(d = {'foo':3, 'bar':{'x':1, 'y':2}}) # 將普通的字典傳入到edict()
print(easy['foo']) # 這是傳統的方法
print(easy.foo) # 這是我們使用easydict輸出二者結果是一樣的,但是可以更為方便的使用字典了
print(easy.bar.x) # 我們也是可以很方便的使用字典中字典的元素了

  



輸出:

3
3
1

3. Easydict的其他用法
3. 1.設置屬性

from easydict import EasyDict as edict
d = edict() # 這個是輸出{}
d.foo = 3 # 我們可以直接賦值語句對字典元素進行創建
d.bar = {'prob':'value'} # 另外我們也可以創建字典中的字典
d.bar.prob = 'newer' # 另外我們也可以很方便的修改字典中元素的值
print(d)

  



輸出:

{'foo': 3, 'bar': {'prob': 'newer'}}
1
3.2 在深度學習中往往利用easydict建立一個全局的變量

from easydict import EasyDict as edict
config = edict()
config.TRAIN = edict() # 創建一個字典,key是Train,值是{}
config.Test = edict()
# config.TRAIN = {} # 這個和上面的那句話是等價的,相當於創建一個字典的key
config.TRAIN.batch_size = 25 # 然后在里面寫值,表示Train里面的value也是一個字典
config.TRAIN.early_stopping_num = 10
config.TRAIN.lr = 0.0001
print(config)

  



輸出:

{'TRAIN': {'batch_size': 25, 'early_stopping_num': 10, 'lr': 0.0001}, 'Test': {}}
1
參考文章

  1. easydict官方網站
  2. ipython筆記



---------------------
作者:alxe_made
來源:CSDN
原文:https://blog.csdn.net/alxe_made/article/details/80507415
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!

 




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM