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

Storing dict keys during traversal #276

Closed therve closed 9 months ago

therve commented 9 months ago

Hi,

I'm struggling to do what seems to be a simple thing when reformatting data, basically store the grandparent dict key when iterating. A simple example:

from glom import *
data = {"a": {"b": {"c": 1}}}

print(
    glom(data, (
        T.values(),
        Iter(T.values()),
        Flatten(),
        [{"value": "c"}]
      )
    )
)  

gives me [{'value': 1}] as I expect. What I'd like is to have [{'value': 1, 'path': 'a'}]. Any idea how to to achieve this? I tried to use S but I never seems to get the scope right. It seems I'm missing something obvious. Thanks!

mahmoud commented 9 months ago

Ah, the grandparent key, sure! This isn't as pretty as I would like, but here's the working spec:

(
        T.items(), 
        Iter(
          (A.globals.gp_item, T[1].values(), 
           Iter({'val': 'c', 
                 'path': S.globals.gp_item[0]}))
        ).flatten().all()
)

And I get:

[
    {
        "val": 1,
        "path": "a"
    }
]

Here's a link to a glompad where you can fool around with it in your browser.

Two key things to note:

Hope this helps!

therve commented 9 months ago

Thanks a lot, I almost reached that one myself! For some reason I was focused on trying to save just the key T[0] instead of the whole items structure, this works.

And a related thank you for that great library.

mahmoud commented 9 months ago

Yeah, I know what you mean re: keys vs items. I might add this example to the docs, in case it's instructive for others too :)