Liq*_*ius 3 python nested python-module data-structures 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.'
},
]
},
]
Run Code Online (Sandbox Code Playgroud)
我试图将数据结构中的所有地址字段提取到扁平的字典列表中。
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)
Run Code Online (Sandbox Code Playgroud)
上述规范规定:
[
{'address': [300]},
{'address': [251]}
]
Run Code Online (Sandbox Code Playgroud)
期望的结果是:
[
{'address':300},
{'address':251},
{'address':4532}
]
Run Code Online (Sandbox Code Playgroud)
从 glom 19.1.0 开始,您可以使用Flatten()规范来简洁地获得您想要的结果:
from glom import glom, Flatten
glom(target, (['addresses'], Flatten(), [{'address': 'address'}]))
# [{'address': 300}, {'address': 251}, {'address': 4532}]
Run Code Online (Sandbox Code Playgroud)
这就是全部!
您可能还想查看方便的 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}]
Run Code Online (Sandbox Code Playgroud)
三个步骤:
'address'键。请注意 的用法T,它代表当前目标,有点像光标。
无论如何,不再需要这样做,部分原因是这个答案。所以,谢谢你提出这个好问题!