首页 > 解决方案 > 使用 Python 模块 Glom,将不规则的嵌套列表提取为扁平的字典列表

问题描述

Glom 使访问复杂的嵌套数据结构变得更加容易。 https://github.com/mahmoud/glom

给定以下玩具数据结构:

target = [
            {
                'user_id': 198,
                'id': 504508,
                'first_name': 'John',
                'last_name': 'Doe',
                'active': True,
                'email_address': 'jd@test.com',
                'new_orders': False,
                'addresses': [
                    {
                        'location': 'home',
                        'address': 300,
                        'street': 'Fulton Rd.'
                    }
                ]
            },
            {
                'user_id': 209,
                'id': 504508,
                'first_name': 'Jane',
                'last_name': 'Doe',
                'active': True,
                'email_address': 'jd@test.com',
                'new_orders': True,
                'addresses': [
                    {
                        'location': 'home',
                        'address': 251,
                        'street': 'Maverick Dr.'
                    },
                    {
                        'location': 'work',
                        'address': 4532,
                        'street':  'Fulton Cir.'
                    },
                ]
            },
        ]

我试图将数据结构中的所有地址字段提取到一个扁平的字典列表中。

from glom import glom as glom
from glom import Coalesce
import pprint

"""
Purpose: Test the use of Glom
"""    

# Create Glomspec
spec = [{'address': ('addresses', 'address') }]

# Glom the data
result = glom(target, spec)

# Display
pprint.pprint(result)

上述规范提供:

[
    {'address': [300]},
    {'address': [251]}
]

期望的结果是:

[
    {'address':300},
    {'address':251},
    {'address':4532}
]

什么 Gromspec 会产生预期的结果?

标签: pythondata-structuresnestedpython-moduleglom

解决方案


从 glom 19.1.0 开始,您可以使用Flatten()规范简洁地获得您想要的结果:

from glom import glom, Flatten

glom(target,  (['addresses'], Flatten(),  [{'address': 'address'}]))
# [{'address': 300}, {'address': 251}, {'address': 4532}]

这就是它的全部!

您可能还想查看方便的 flatten() 函数以及强大的Fold() 规范,以满足您所有的展平需求:)


在 19.1.0 之前,glom 没有一流的扁平化或缩减(如 map-reduce)功能。但一种解决方法是使用 Python 的内置sum()函数来展平地址:

>>> from glom import glom, T, Call  # pre-19.1.0 solution
>>> glom(target,  ([('addresses', [T])], Call(sum, args=(T, [])),  [{'address': 'address'}]))
[{'address': 300}, {'address': 251}, {'address': 4532}]

三个步骤:

  1. 像您所做的那样遍历列表。
  2. 在结果列表上调用 sum,将其展平/减少。
  3. 过滤结果列表中的项目以仅包含'address'键。

注意 代表当前目标的用法T,有点像游标。

无论如何,不​​再需要这样做,部分原因是这个答案。所以,谢谢你的好问题!


推荐阅读