最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python黑魔法庫安裝及操作字典示例詳解

 更新時間:2021年10月25日 15:17:44   作者:寫代碼的明哥  
這篇文章主要為大家介紹了Python中黑魔法庫的安裝及操作字典的示例詳解,有需要的 朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步

本篇文章收錄于《Python黑魔法手冊》v3.0 第七章,手冊完整版在線閱讀地址:Python黑魔法手冊 3.0 文檔

字典是 Python 中基礎(chǔ)的數(shù)據(jù)結(jié)構(gòu)之一,字典的使用,可以說是非常的簡單粗暴,但即便是這樣一個與世無爭的數(shù)據(jù)結(jié)構(gòu),仍然有很多人 “用不慣它” 。

也許你并不覺得,但我相信,你看了這篇文章后,一定會和我一樣,對原生字典開始有了偏見。

我舉個簡單的例子吧

當(dāng)你想訪問字典中的某個 key 時,你需要使用字典特定的訪問方式,而這種方式需要你鍵入 一對中括號 還有 一對引號

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

是不是開始覺得忍無可忍了?

如果可以像調(diào)用對象屬性一樣使用 . 去訪問 key 就好了,可以省去很多多余的鍵盤擊入,就像這樣子

>>> profile.name
'iswbm'

是的,今天這篇文章就是跟大家分享一種可以直接使用 . 訪問和操作字典的一個黑魔法庫 – munch。

1. 安裝方法

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

$ python -m pip install munch

2. 簡單示例

munch 有一個 Munch 類,它繼承自原生字典,使用 isinstance 可以驗證

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

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

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

3. 兼容字典的所有操作

本身 Munch 繼承自 dict,dict 的操作也同樣適用于 Munch 對象,不妨再來驗證下

首先是:增刪改查

# 新增元素
>>> 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)訪問一個字典中不存在的 key 時,會報 KeyError 的錯誤

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

對于這種情況,通常我們會使用 get 來規(guī)避

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

當(dāng)然你在 munch 中仍然可以這么用,不過還有一種更好的方法:使用 DefaultMunch,它會在你訪問不存在的 key 時,給你返回一個設(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ù)自動創(chuàng)建key

上面使用 DefaultMunch 僅當(dāng)你訪問不存在的 key 是返回一個默認(rèn)值,但這個行為并不會修改原 munch 對象的任何內(nèi)容。

若你想訪問不存在的 key 時,自動觸發(fā)給原 munch 中新增你想要訪問的 key ,并為其設(shè)置一個默認(rèn)值,可以試一下 DefaultFactoryMunch 傳入一個工廠函數(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 格式的字符串對象

轉(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

>>> dict_obj = {"1.2": "hello"}
>>> dict_obj["1.2"]
'hello'

7. 說說局限性

以上就是關(guān)于 munch 的使用全解,munch 的進(jìn)一步封裝使得數(shù)據(jù)的訪問及操作更得更加 Pythonic ,替換原生字典在大部分場景下都不會有太大問題。

但同時也不得不承認(rèn),munch 在一些場景下無法達(dá)到原生字典的效果,比如我想字典里的 key 為 "1.2" 的時候,原生字典能很好的表示它。

>>> dict_obj = {"1.2": "hello"}
>>> dict_obj["1.2"]
'hello'

切換到 munch ,你會發(fā)現(xiàn)無法在初始化 munch 對象的時候,傳入 1.2 的 key

>>> from munch import Munch
>>> dict_obj = Munch(1.2="hello")
  File "<stdin>", line 1
    dict_obj = Munch(1.2="hello")
                     ^
SyntaxError: expression cannot contain assignment, perhaps you meant "=="?

就算你用原生的字典的方式添加了這個 key-value,也根本無法使用 . 的方式取到 1.2 對應(yīng)的 value。

>>> from munch import Munch
>>> dict_obj = Munch()
>>> dict_obj["1.2"]="hello"
>>> dict_obj
Munch({'1.2': 'hello'})
>>> dict_obj.1.2
  File "<stdin>", line 1
    dict_obj.1.2
            ^
SyntaxError: invalid syntax

也正是因為這樣,原生字典至今還是不可替代的存在。

以上就今天跟大家分享的內(nèi)容,這篇文章是《Python黑魔法手冊》 v3.0 版的最后一篇文章,目前 PDF 已經(jīng)制作完成。

這本手冊目前已經(jīng)發(fā)布到了 Github,點(diǎn)擊這個鏈接即可下載:Release v3.0 · iswbm/magic-python

以上就是Python黑魔法庫安裝及操作字典示例詳解的詳細(xì)內(nèi)容,更多關(guān)于黑魔法庫安裝及操作的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • python實(shí)現(xiàn)簡單聊天室功能 可以私聊

    python實(shí)現(xiàn)簡單聊天室功能 可以私聊

    這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)簡單聊天室功能,可以進(jìn)行私聊,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-07-07
  • 利用Python實(shí)現(xiàn)簡易計算器的示例代碼

    利用Python實(shí)現(xiàn)簡易計算器的示例代碼

    最近學(xué)習(xí)了字符串,運(yùn)算符,條件語句,循環(huán)語句,我在想可以用我最近學(xué)的東西做什么? 看到運(yùn)算我就想到了可以做一個簡易的計算器,感興趣的可以了解一下
    2022-11-11
  • Python中操作文件之write()方法的使用教程

    Python中操作文件之write()方法的使用教程

    這篇文章主要介紹了Python中操作文件之write()方法的使用教程,是Python入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下
    2015-05-05
  • pyinstaller還原python代碼過程圖解

    pyinstaller還原python代碼過程圖解

    這篇文章主要介紹了pyinstaller還原python代碼過程圖解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-01-01
  • Python的 元組(Tuple)詳解

    Python的 元組(Tuple)詳解

    Python的元組與列表類似,不同之處在于元組的元素不能修改,元組使用小括號,列表使用方括號,元組創(chuàng)建很簡單,只需要在括號中添加元素,并使用逗號隔開即可
    2021-10-10
  • 使用Python來開發(fā)微信功能

    使用Python來開發(fā)微信功能

    這篇文章主要介紹了使用Python來開發(fā)微信功能,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下
    2018-06-06
  • Python讀取環(huán)境變量的方法和自定義類分享

    Python讀取環(huán)境變量的方法和自定義類分享

    這篇文章主要介紹了Python讀取環(huán)境變量的方法和自定義類分享,本文直接給出代碼實(shí)例,需要的朋友可以參考下
    2014-11-11
  • Pytorch實(shí)現(xiàn)簡單自定義網(wǎng)絡(luò)層的方法

    Pytorch實(shí)現(xiàn)簡單自定義網(wǎng)絡(luò)層的方法

    這篇文章主要給大家介紹了關(guān)于Pytorch實(shí)現(xiàn)簡單自定義網(wǎng)絡(luò)層的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2022-05-05
  • Python Tkinter模塊 GUI 可視化實(shí)例

    Python Tkinter模塊 GUI 可視化實(shí)例

    今天小編就為大家分享一篇Python Tkinter模塊 GUI 可視化實(shí)例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-11-11
  • jupyter安裝小結(jié)

    jupyter安裝小結(jié)

    jupyter (之前的 ipython notebook )于我的最大意義在于,讓學(xué)習(xí)進(jìn)程和探索進(jìn)程變得可累積,正如它的原先名字中的 notebook 所暗示的那樣,作為學(xué)習(xí)的記錄者,方便你隨時撿起學(xué)習(xí)的進(jìn)度,增量式地前進(jìn)
    2016-03-03

最新評論

南江县| 德庆县| 比如县| 湖南省| 汤阴县| 四子王旗| 铜梁县| 沧州市| 泰安市| 尉犁县| 天镇县| 历史| 长顺县| 望谟县| 长岭县| 樟树市| 新津县| 武夷山市| 肇州县| 广平县| 噶尔县| 澄迈县| 错那县| 深圳市| 瑞金市| 德清县| 朝阳区| 广南县| 凯里市| 南皮县| 华蓥市| 耿马| 永胜县| 依兰县| 吉木乃县| 庆阳市| 西平县| 奎屯市| 齐齐哈尔市| 灵川县| 平湖市|