Addit 是一個Python模塊,除了提供標準的字典語法外,Addit 生成的字典的值既可以使用屬性來獲取,也可以使用屬性進行設置。
這意味著你不用再寫這樣的字典了:
body = {
'query': {
'filtered': {
'query': {
'match': {'description': 'addictive'}
},
'filter': {
'term': {'created_by': 'Mats'}
}
}
}
}
相反,你只需編寫以下三行代碼就能完成目的:
body = Dict()
body.query.filtered.query.match.description = 'addictive'
body.query.filtered.filter.term.created_by = 'Mats'
1.安裝
你可以通過pip安裝:
pip installaddict
或通過conda:
conda installaddict -c conda-forge
Addit 在Python2.7+和Python3上都可以運行。
2.用法
Addict 繼承自字典,但在訪問和設置其值方面更加靈活。使用 Addict 的字典是一種樂趣!
設置嵌套詞典的項是極其舒服的:
>>> from addict import Dict
>>> mapping = Dict()
>>> mapping.a.b.c.d.e = 2
>>> mapping
{'a': {'b': {'c': {'d': {'e': 2}}}}}
如果Dict是用任何可迭代值實例化的,它將遍歷并克隆這些值,然后寫入到對應的屬性及值中,比如:
>>> mapping = {'a': [{'b': 3}, {'b': 3}]}
>>> dictionary = Dict(mapping)
>>> dictionary.a[0].b
3
但mapping['a']不再與dictionary['a']相同。
>>> mapping['a'] is dictionary['a']
False
當然,此特點僅限于構造函數(shù),而不是在使用屬性或設置值時:
>>> a = Dict()
>>> b = [1, 2, 3]
>>> a.b = b
>>> a.b is b
True
3.要牢記的事情
記住,int不是有效的屬性名,因此必須使用 get/setitem 語法 設置/獲取 非字符串的 dict 鍵:
>>> mapping = Dict()
>>> mapping.keys = 2
Traceback (most recent call last):
File "", line 1, in
File "addict/addict.py", line 53, in __setattr__
raise AttributeError("'Dict' object attribute '%s' is read-only" % name)
AttributeError: 'Dict' object attribute 'keys' is read-only
不過,你可以隨意混合使用這兩種語法:
>>> addicted.a.b['c'].d.e
2
4.屬性,如鍵、item等
Addit 不會讓你覆蓋dict的屬性,因此以下操作將不起作用:
>>> mapping = Dict()
>>> mapping.keys = 2
Traceback (most recent call last):
File "", line 1, in
File "addict/addict.py", line 53, in __setattr__
raise AttributeError("'Dict' object attribute '%s' is read-only" % name)
AttributeError: 'Dict' object attribute 'keys' is read-only
不過,使用下面這種方式就可以:
>>> a = Dict()
>>> a['keys'] = 2
>>> a
{'keys': 2}
>>> a['keys']
2
5.默認值
對于不在字典中的鍵,Addit的行為如defaultdict(Dict),因此丟失的鍵返回一個空的Dict而不是拋出KeyError如果此行為不是所需的,則可以使用以下方式恢復拋出KeyError:
>>> class DictNoDefault(Dict):
>>> def __missing__(self, key):
>>> raise KeyError(key)
但請注意,這樣會失去速記賦值功能(addicted.a.b.c.d.e = 2)
6.轉化為普通字典
如果你覺得將 Addict 傳遞到其他函數(shù)或模塊并不安全,請使用to_dict()方法,它返回會把 Addict 轉化為普通字典。
>>> regular_dict = my_addict.to_dict()
>>> regular_dict.a = 2
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'dict' object has no attribute 'a'
當您希望在幾行代碼中創(chuàng)建嵌套的字典,然后將其發(fā)送到不同的函數(shù)或模塊時,這非常適合:
body = Dict()
body.query.filtered.query.match.description = 'addictive'
body.query.filtered.filter.term.created_by = 'Mats'
third_party_module.search(query=body.to_dict())
7.計數(shù)
Dict輕松訪問和修改深度嵌套屬性的能力使其成為計數(shù)的理想選擇。使用Addict,你還可以容易允許按多個級別計數(shù),內(nèi)部使用的原理是collections.Counter。
比如以下數(shù)據(jù):
data = [
{'born': 1980, 'gender': 'M', 'eyes': 'green'},
{'born': 1980, 'gender': 'F', 'eyes': 'green'},
{'born': 1980, 'gender': 'M', 'eyes': 'blue'},
{'born': 1980, 'gender': 'M', 'eyes': 'green'},
{'born': 1980, 'gender': 'M', 'eyes': 'green'},
{'born': 1980, 'gender': 'F', 'eyes': 'blue'},
{'born': 1981, 'gender': 'M', 'eyes': 'blue'},
{'born': 1981, 'gender': 'F', 'eyes': 'green'},
{'born': 1981, 'gender': 'M', 'eyes': 'blue'},
{'born': 1981, 'gender': 'F', 'eyes': 'blue'},
{'born': 1981, 'gender': 'M', 'eyes': 'green'},
{'born': 1981, 'gender': 'F', 'eyes': 'blue'}
]
如果你想計算有多少人出生在born性別的gender使用eyes眼睛,你可以很容易地計算出這些信息:
counter = Dict()
for row in data:
born = row['born']
gender = row['gender']
eyes = row['eyes']
counter[born][gender][eyes] += 1 print(counter)
# 結果:{1980: {'M': {'blue': 1, 'green': 3}, 'F': {'blue': 1, 'green': 1}}, 1981: {'M': {'blue': 2, 'green': 1}, 'F': {'blue': 2, 'green': 1}}}
8.更新
普通字典的更新方式如下:
>>> d = {'a': {'b': 3}}
>>> d.update({'a': {'c': 4}})
>>> print(d)
{'a': {'c': 4}}
addict的更新方式如下,它會遞歸并實際更新嵌套的字典:
>>> D = Dict({'a': {'b': 3}})
>>> D.update({'a': {'c': 4}})
>>> print(D)
{'a': {'b': 3, 'c': 4}}
9.Addict 是怎么來的?
這個模塊完全是從用Python創(chuàng)建Elasticsearch查詢的繁瑣過程中發(fā)展而來的。每當你發(fā)現(xiàn)自己在寫了很復雜的字典邏輯時,只要記住你沒有必要這樣做,使用 Addict 就行。
審核編輯:湯梓紅
-
模塊
+關注
關注
7文章
2822瀏覽量
52804 -
代碼
+關注
關注
30文章
4941瀏覽量
73152 -
python
+關注
關注
57文章
4858瀏覽量
89591
發(fā)布評論請先 登錄
Termux中調(diào)試圣誕樹Python代碼
毫米波雷達模塊選型與安裝指南:minewsemi雷達模塊打造精準感知系統(tǒng)
MA35-RTT如何安裝 Python 和 Libusb (Windows) ?
termux調(diào)試python猜數(shù)字游戲
termux如何搭建python游戲
MCU數(shù)據(jù)采集模塊安裝與配置實踐指南
linux虛擬環(huán)境中調(diào)用Linux 版matlab編譯的python庫時出錯
Hi3861 wifiiot_hispark_pegasus 按教程安裝python3 -m pip install build/lite 報錯
?如何在虛擬環(huán)境中使用 Python,提升你的開發(fā)體驗~
運行OVModelForCausalLM Python模塊時出錯了,怎么解決?
使用Python實現(xiàn)xgboost教程
Flexus 云服務器 X:Python 安裝的極致便捷之旅
華為云 Flexus X 實例下的場景體驗——小企業(yè)使用 Python 語言——超迅速搭建簡單公網(wǎng) API 接口服務

Python模塊Addict的安裝與使用
評論