複雜嵌套字典數據結構處理庫-glom

經常遇到複雜嵌套字典數據,我們都是這麼寫的


data = {'a': {'b': {'c': 'd'}}}

print(data['a']['b']['c'])
'd'

然後經常遇到這個bug


data2 = {'a': {'b': None}}

print(data2['a']['b']['c'])
Traceback (most recent call last):
...
TypeError: 'NoneType' object is not subscriptable

有沒有覺得['a']['b']['c']這樣寫既麻煩,還不靠譜。glom的出現可以完美的解決這個問題。

glom地址 https://github.com/mahmoud/glom

Python's nested data operator (and CLI), for all your declarative restructuring needs.

python嵌套數據操作庫,滿足您所有的數據重構需要。

一、glom.glom
glom.glom(target, spec,kwargs)

  • target:你傳入的字典數據

  • spec:關鍵詞路徑。相當於過去的['a']['b']['c'],但是在glom中,路徑的寫法簡化爲'a.b.c'

  • default:如果字典中沒有關鍵詞,那麼返回默認default的值。

  • skip_exc:一個可選的異常異常或元組忽略並返回默認值。如果glom中沒有設置default和skip_exc,那麼會引起報錯。

具體代碼


from glom import glom

data = {'a': {'b': {'c': 'd'}}}

print(glom(data, 'a.b.c'))

#data中沒有d這個key,設置default後就不會保存
print(glom(data, 'a.b.c.d', default='錯了'))

#沒有設置default,報錯
print(glom(data, 'a.b.c.d'))
d

錯了

raise PathAccessError(e, parts, i)
glom.core.PathAccessError: could not access 'd', index 3 in path Path('a', 'b', 'c', 'd'), got error: AttributeError("'str' object has no attribute 'd'",)

二、glom.Path
上面關鍵詞順序'a.b.c'在大部分都是可以用的。但是有時候字典中的key是帶有 '.'的,或者key是整數數字,剛剛的方法會有問題。


target = {'a': {'b': 'c', 'd.e': 'f', 2: 3}}

print(glom(target, 'a.2'))

print(glom(target, 'a.d.e'))
KeyError: '2'
During handling of the above exception, another exception occurred:

glom.core.PathAccessError: could not access '2', index 1 in path Path('a', '2'), got error: KeyError('2',)

這時候我們需要使用Path來處理這些情況。


from glom import glom, Path

target = {'a': {'b': 'c', 'd.e': 'f', 2: 3}}

print(glom(target, Path('a', 2)))

print(glom(target, Path('a', 'd.e')))
3
f

三、glom.Literal
有時候我們需要對字典數據進行替換操作。 如


target = {'a': {'b': 'c'}}
target['a'] = target['a']['b']
target['readability'] = 'counts'

print(target)
{'a': 'c', 'readability': 'counts'}

而在glom中,是這樣實現的。Literal告訴glom.glom我這次傳入的是value,而不是字典的key。


target = {'a': {'b': 'c'}}

spec = {'a': 'a.b', 'readability': Literal('counts')}

print(glom(target, spec))
{'a': 'c', 'readability': 'counts'}

四、glom.Coalesce
有時候我們不知道字典中有哪些關鍵詞,這時候可能要一個個的試驗。在glom中提供了Coalesce,可以給glom.glom我傳入的是多個key,你都給在字典裏找找,找到了告訴我結果。


target = {'c': 'd'}

print(glom(target, Coalesce('a', 'b', 'c')))
d

假如字典中一個都沒找到,會引起程序報錯。所以我們要設置default參數。


target = {}

print(glom(target, Coalesce('a', 'b', 'c'), default='d-fault'))
d-fault

五、glom.OMIT
OMIT意思是移除。在glom.glom中的spec參數這裏我們可以傳入含有lambda表達式的字典。

下面代碼中的t指代target字典本身。如果target['a']=='a',那麼target不變。

如果target['a']!=='a',那麼OMIT,即移除。

target = {'a': 'b'}

spec = {'a': lambda t: t['a'] if t['a'] == 'a' else OMIT}

print(glom(target, spec))
{}
target = {'a': 'a'}

print(glom(target, spec))
{'a': 'b'}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章