Anthony Chung Anthony Chung - 7 months ago 24
Python Question

python - split array of objects

I have a data structure that looks like this

arrayObjects = [{id: 1, array1: [a,b,c]}, {id: 2, array1: [d,e,f]}]

and would like to transform it into this:

newArrayObjects = [{id: 1, term: a}, {id:1, term: b}, ... {id:2, term: f} ]

any idea on how to do this?

this is my minimum version right now:

for item in arrayObjects:
for term in item['array1']:
print(term, item['id'])

to clarify: I know how to do this with a nested loop, I'm just going for the most pythonic version possible haha


You can use list comprehension:

>>> a = [{'id': 1, 'array': ['a','b','c']}, {'id': 2, 'array': ['d','e','f']}]
>>> [{'id': d['id'], 'term': v } for d in a for v in d['array']]
[{'term': 'a', 'id': 1}, {'term': 'b', 'id': 1}, {'term': 'c', 'id': 1}, {'term': 'd', 'id': 2}, {'term': 'e', 'id': 2}, {'term': 'f', 'id': 2}]