主頁(yè) > 知識(shí)庫(kù) > python munch庫(kù)的使用解析

python munch庫(kù)的使用解析

熱門標(biāo)簽:河北防封卡電銷卡 應(yīng)電話機(jī)器人打電話違法嗎 地圖標(biāo)注線上如何操作 電銷機(jī)器人的風(fēng)險(xiǎn) 400電話辦理哪種 天津電話機(jī)器人公司 手機(jī)網(wǎng)頁(yè)嵌入地圖標(biāo)注位置 開封語(yǔ)音外呼系統(tǒng)代理商 開封自動(dòng)外呼系統(tǒng)怎么收費(fèi)

字典是 Python 中基礎(chǔ)的數(shù)據(jù)結(jié)構(gòu)之一,字典的使用,可以說(shuō)是非常的簡(jiǎn)單粗暴,但即便是這樣一個(gè)與世無(wú)爭(zhēng)的數(shù)據(jù)結(jié)構(gòu),仍然有很多人 "看不慣它" 。
也許你并不覺得,但我相信,你看了這篇文章后,一定會(huì)和我一樣,對(duì)原生字典開始有了偏見。
我舉個(gè)簡(jiǎn)單的例子吧
當(dāng)你想訪問(wèn)字典中的某個(gè) key 時(shí),你需要使用字典特定的訪問(wèn)方式,而這種方式需要你鍵入 一對(duì)中括號(hào) 還有 一對(duì)引號(hào)

>>> profile = dict(name="iswbm")
>>> profile
{'name': 'iswbm'}
>>> profile["name"]
'iswbm'

是不是開始覺得忍無(wú)可忍了?
如果可以像調(diào)用對(duì)象屬性一樣使用 . 去訪問(wèn) key 就好了,可以省去很多多余的鍵盤擊入,就像這樣子

>>> profile.name
'iswbm'

是的,今天這篇文章就是跟大家分享一種可以直接使用 . 訪問(wèn)和操作字典的一個(gè)黑魔法庫(kù) -- munch。

1. 安裝方法

使用如下命令進(jìn)行安裝

$ python -m pip install munch

2. 簡(jiǎn)單示例

munch 有一個(gè) Munch 類,它繼承自原生字典,使用 isinstance 可以驗(yàn)證

>>> from munch import Munch
>>> profile = Munch()
>>> isinstance(profile, dict)
True
>>>

并實(shí)現(xiàn)了點(diǎn)式賦值與訪問(wèn),profile.name 與 profile['name'] 是等價(jià)的

>>> profile.name = "iswbm"
>>> profile.age = 18
>>> profile
Munch({'name': 'iswbm', 'age': 18})
>>>
>>> profile.name
'iswbm'
>>> profile["name"]
'iswbm'

3. 兼容字典的所有操作

本身 Munch 繼承自 dict,dict 的操作也同樣適用于 Munch 對(duì)象,不妨再來(lái)驗(yàn)證下
首先是:增刪改查

# 新增元素
>>> profile["gender"] = "male"
>>> profile
Munch({'name': 'iswbm', 'age': 18, 'gender': 'male'})

# 修改元素
>>> profile["gender"] = "female"
>>> profile
Munch({'name': 'iswbm', 'age': 18, 'gender': 'female'})

# 刪除元素
>>> profile.pop("gender")
'female'
>>> profile
Munch({'name': 'iswbm', 'age': 18})
>>>
>>> del profile["age"]
>>> profile
Munch({'name': 'iswbm'})

再者是:一些常用方法

>>> profile.keys()
dict_keys(['name'])
>>>
>>> profile.values()
dict_values(['iswbm'])
>>>
>>> profile.get('name')
'iswbm'
>>> profile.setdefault('gender', 'male')
'male'
>>> profile
Munch({'name': 'iswbm', 'gender': 'male'})

4. 設(shè)置返回默認(rèn)值

當(dāng)訪問(wèn)一個(gè)字典中不存在的 key 時(shí),會(huì)報(bào) KeyError 的錯(cuò)誤

>>> profile = {}
>>> profile["name"]
Traceback (most recent call last):
  File "stdin>", line 1, in module>
KeyError: 'name'

對(duì)于這種情況,通常我們會(huì)使用 get 來(lái)規(guī)避

>>> profile = {}
>>> profile.get("name", "undefined")
'undefined'

當(dāng)然你在 munch 中仍然可以這么用,不過(guò)還有一種更好的方法:使用 DefaultMunch,它會(huì)在你訪問(wèn)不存在的 key 時(shí),給你返回一個(gè)設(shè)定好的默認(rèn)值

>>> from munch import DefaultMunch
>>> profile = DefaultMunch("undefined", {"name": "iswbm"})
>>> profile
DefaultMunch('undefined', {'name': 'iswbm'})
>>> profile.age
'undefined'
>>> profile
DefaultMunch('undefined', {'name': 'iswbm'})

5. 工廠函數(shù)自動(dòng)創(chuàng)建key

上面使用 DefaultMunch 僅當(dāng)你訪問(wèn)不存在的 key 是返回一個(gè)默認(rèn)值,但這個(gè)行為并不會(huì)修改原 munch 對(duì)象的任何內(nèi)容。
若你想訪問(wèn)不存在的 key 時(shí),自動(dòng)觸發(fā)給原 munch 中新增你想要訪問(wèn)的 key ,并為其設(shè)置一個(gè)默認(rèn)值,可以試一下 DefaultFactoryMunch 傳入一個(gè)工廠函數(shù)。

>>> from munch import DefaultFactoryMunch
>>> profile = DefaultFactoryMunch(list, name='iswbm')
>>> profile
DefaultFactoryMunch(list, {'name': 'iswbm'})
>>>
>>> profile.brothers
[]
>>> profile
DefaultFactoryMunch(list, {'name': 'iswbm', 'brothers': []})

6. 序列化的支持

Munch 支持序列化為 JSON 或者 YAML 格式的字符串對(duì)象
轉(zhuǎn)換成 JSON

>>> from munch import Munch
>>> munch_obj = Munch(foo=Munch(lol=True), bar=100, msg='hello')
>>>
>>> import json
>>> json.dumps(munch_obj)
'{"foo": {"lol": true}, "bar": 100, "msg": "hello"}'

轉(zhuǎn)換成 YAML

>>> from munch import Munch
>>> munch_obj = Munch(foo=Munch(lol=True), bar=100, msg='hello')
>>> import yaml
>>> yaml.dump(munch_obj)
'!munch.Munch\nbar: 100\nfoo: !munch.Munch\n  lol: true\nmsg: hello\n'
>>>
>>> print(yaml.dump(munch_obj))
!munch.Munch
bar: 100
foo: !munch.Munch
  lol: true
msg: hello

>>>

建議使用 safe_dump 去掉 !munch.Munch

>>> print(yaml.safe_dump(munch_obj))
bar: 100
foo:
  lol: true
msg: hello

以上就是關(guān)于 munch 的使用全解,替換原生字典絕無(wú)問(wèn)題,munch 的進(jìn)一步封裝使得數(shù)據(jù)的訪問(wèn)及操作更得更加 Pythonic 了,希望有一天這個(gè)特性能夠體現(xiàn)在原生的字典上。

到此這篇關(guān)于python munch庫(kù)的使用解析的文章就介紹到這了,更多相關(guān)python munch庫(kù)的使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:
  • python 實(shí)用工具狀態(tài)機(jī)transitions
  • 簡(jiǎn)單理解Python中基于生成器的狀態(tài)機(jī)
  • 狀態(tài)機(jī)的概念和在Python下使用狀態(tài)機(jī)的教程
  • 淺談python中常用的excel模塊庫(kù)
  • Python 中拼音庫(kù) PyPinyin 用法詳解
  • 教你使用Python pypinyin庫(kù)實(shí)現(xiàn)漢字轉(zhuǎn)拼音
  • Python爬蟲基礎(chǔ)之selenium庫(kù)的用法總結(jié)
  • python爬蟲之selenium庫(kù)的安裝及使用教程
  • python狀態(tài)機(jī)transitions庫(kù)詳解

標(biāo)簽:宿遷 常州 蘭州 成都 六盤水 駐馬店 江蘇 山東

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《python munch庫(kù)的使用解析》,本文關(guān)鍵詞  python,munch,庫(kù),的,使用,解析,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《python munch庫(kù)的使用解析》相關(guān)的同類信息!
  • 本頁(yè)收集關(guān)于python munch庫(kù)的使用解析的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章