Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enumerate and Assign #272

Closed
boonhapus opened this issue Oct 29, 2023 · 2 comments
Closed

Enumerate and Assign #272

boonhapus opened this issue Oct 29, 2023 · 2 comments

Comments

@boonhapus
Copy link

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
Copy link
Author

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
Copy link
Owner

mahmoud commented Oct 30, 2023

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

@mahmoud mahmoud closed this as completed Oct 30, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants