選單

聽說這個庫要終結 Python 原生字典?

大家好,歡迎來到 Crossin的程式設計教室 !

今天來聊一聊與字典相關的話題。

字典是 Python 中基礎的資料結構之一,字典的使用,可以說是非常的簡單粗暴,但即便是這樣一個與世無爭的資料結構,仍然有很多人 “看不慣它” 。

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

我舉個簡單的例子吧

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

>>> profile = dict(name=“iswbm”)

>>> profile

{‘name’: ‘iswbm’}

>>> profile[“name”]

‘iswbm’

是不是覺得有點囉嗦?

如果可以像呼叫物件屬性一樣使用 去訪問 key 就好了,可以省去很多次的鍵盤敲擊,就像這樣子

>>> profile。name

‘iswbm’

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

1。 安裝方法

使用如下命令進行安裝

$ python -m pip install munch

2。 簡單示例

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

>>> from munch import Munch

>>> profile = Munch()

>>> isinstance(profile, dict)

True

>>>

並實現了點式賦值與訪問, 與 是等價的

>>> 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。 設定返回預設值

當訪問一個字典中不存在的 key 時,會報 KeyError 的錯誤

>>> profile = {}

>>> profile[“name”]

Traceback (most recent call last):

File “”, line 1, in

KeyError: ‘name’

對於這種情況,通常我們會使用 get 來規避

>>> profile = {}

>>> profile。get(“name”, “undefined”)

‘undefined’

當然你在 munch 中仍然可以這麼用,不過還有一種更好的方法:使用 DefaultMunch,它會在你訪問不存在的 key 時,給你返回一個設定好的預設值

>>> from munch import DefaultMunch

>>> profile = DefaultMunch(“undefined”, {“name”: “iswbm”})

>>> profile

DefaultMunch(‘undefined’, {‘name’: ‘iswbm’})

>>> profile。age

‘undefined’

>>> profile

DefaultMunch(‘undefined’, {‘name’: ‘iswbm’})

5。 工廠函式自動建立key

上面使用 僅當你訪問不存在的 key 是返回一個預設值,但這個行為並不會修改原 munch 物件的任何內容。

若你想訪問不存在的 key 時,自動觸發給原 munch 中新增你想要訪問的 key ,併為其設定一個預設值,可以試一下 傳入一個工廠函式。

>>> 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 格式的字串物件

轉換成 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”}’

轉換成 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

>>>

建議使用 去掉

>>> print(yaml。safe_dump(munch_obj))

bar: 100

foo:

lol: true

msg: hello

以上就是關於 munch 的使用全解,替換原生字典絕無問題,munch 的進一步封裝使得資料的訪問及操作更得更加 Pythonic 了,希望有一天這個特效能夠體現在原生的字典上。