gpt4 book ai didi

python - Glom 处理或跳过具有不同键的数据的 PathError?

转载 作者:行者123 更新时间:2023-12-05 07:14:39 26 4
gpt4 key购买 nike

我正在使用 glom 包来帮助遍历一个大字典。

鉴于此数据:

data = {
'groups': [
{'instance': {'name': 'football'}},
{'instance': {'name': 'rugby'}},
{'id': 145, 'type': 'unknown'},
]
}

然后使用 glom,我尝试获取实例名称:

import glom
instance_names = glom(data, ('groups', ['instance.name']))

我收到一个错误:

glom.core.PathAccessError: could not access 'instance', part 0 of Path('instance', 'name'), got error: KeyError('instance')

如何跳过 instance 键不存在的对象?

更新

我试图跳过异常,但随后收到空结果:

instance_names = glom(data, ('groups', ['instance.name']), skip_exc=PathAccessError)

最佳答案

根据 glom 的文档API。

default (object) – An optional default to return in the case an exception, specified by skip_exc, is raised.

skip_exc (Exception) – An optional exception or tuple of exceptions to ignore and return default (None if omitted). If skip_exc and default are both not set, glom

所以

instance_names = glom(data, ('groups', ['instance.name']), skip_exc=PathAccessError)

遇到PathAccessError异常时会返回default(None)。这是 relevant part解释这一点的源代码。

default = kwargs.pop('default', None if 'skip_exc' in kwargs else _MISSING)
skip_exc = kwargs.pop('skip_exc', () if default is _MISSING else GlomError)
...
...
try:
ret = _glom(target, spec, scope)
except skip_exc:
if default is _MISSING:
raise
ret = default

这是解决此问题的一种方法。

Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from glom import glom, SKIP
>>>
>>> data = {
... 'groups': [
... {'instance': {'name': 'football'}},
... {'instance': {'name': 'rugby'}},
... {'id': 145, 'type': 'unknown'},
... ]
... }
>>>
>>> instance_names = glom(data, ('groups', [lambda x: glom(x, 'instance.name', default=SKIP)]))
>>> print(instance_names)
['football', 'rugby']

SKIP singleton可以从函数返回或通过文字包含以取消对输出对象的赋值。

关于python - Glom 处理或跳过具有不同键的数据的 PathError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59837288/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com