您的位置:首页 > 理论基础 > 数据结构算法

复杂嵌套字典数据结构处理库-glom

2021-01-03 22:21 1061 查看

经常遇到复杂嵌套字典数据,我们都是这么写的

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'}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: