Glom处理或跳过具有不同密钥的数据的PathError?

2024-10-04 07:33:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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)

Tags: 数据实例instancenameiddatanamestype
1条回答
网友
1楼 · 发布于 2024-10-04 07:33:32

根据^{}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异常时,将返回默认值(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']

可以从函数返回^{} singleton,也可以通过文本包含^{} singleton,以取消对输出对象的赋值

相关问题 更多 >