mahmoud / glom

☄️ Python's nested data operator (and CLI), for all your declarative restructuring needs. Got data? Glom it! ☄️
https://glom.readthedocs.io
Other
1.88k stars 61 forks source link

Enumerate and Assign #272

Closed boonhapus closed 9 months ago

boonhapus commented 10 months ago

I'm ingesting data from an API that I want to enumerate, and assign that enumeration to an ID field. You can imagine that the data is sometimes in the order I want, and sometimes I am required to order it myself -- essentially what's below is a MVE, but the concept is still the same.

>>> from glom import glom, T, A, S, Assign
>>>
>>> data = [
...     {"letter": "a"},
...     {"letter": "b"},
...     {"letter": "c"},
... ]
>>>
>>> spec = (
...     enumerate,
...     [
...         (
...             Assign(T[1]["id"], T[0]),
...             T[1]
...         )
...     ]
... )
>>>
>>> glom(data, spec)
[
    {"letter": "a", "id": 0},
    {"letter": "b", "id": 1},
    {"letter": "c", "id": 2}
]

While I've got this working, it's feels really terse and I'm curious if there's a better way here.

boonhapus commented 10 months ago

This spec seems WAY more readable. 😃 I found the example from this old issue, totally didn't think of simply calling dict on the existing mapping, which is totally what I want.

spec = (
    enumerate,
    [Invoke(dict).specs(T[1], id=T[0])]
)
mahmoud commented 9 months ago

Awesome! Thanks for checking past issues. I sometimes mine those for tips, too. If this sort of thing comes up often enough, maybe we can make it a snippet? https://glom.readthedocs.io/en/latest/snippets.html