简体   繁体   中英

Use glom to get Index while iterating over an list of dictionaries

from glom import glom, T
from glom.core import Val


target = [
    {"firstname": 'boka', 'lastname':'raton'},
    {"firstname": 'cape', 'lastname':'town'}
]
spec = ([{
    'fname':'firstname',
    'index': Val('0')
}])

r = glom(target, spec)
print(r)

Is it possible to capture the index while iterating over a list of dictionaries using glom?
The current output is:

[{'fname': 'boka', 'index': '0'}, {'fname': 'cape', 'index': '0'}].   

But I'd like to have the following:

[{'fname': 'boka', 'index': 0}, {'fname': 'cape', 'index': 1}]

Solved it by enumerating over the items and performing glom on one dictionary at a time.
Used the Val to evaluate the wrapped value of index

from glom import glom
from glom.core import Val
result = []
for index, value in enumerate(target):
    spec = {
        'fname': 'firstname',
        'index': Val(index)
    }
    r = glom(value, spec)
    result.append(r)
print(result)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM