1

I have an array of dict like:

[{'id': 1, 'tags': ['tag_a', 'tag_b']}, {'id': 2, 'tags': ['tag_c', 'tag_b']}]

and I would like to convert this array into a new array based on ticket_id and each tag value should be an object in the array.

I almost did it using the following function:

raw = [{'id': 1, 'tags': ['tag_a', 'tag_b']}, {'id': 2, 'tags': ['tag_c', 'tag_b']}]

def transform(ticket):
    result = []
    for tag in ticket.get('tags', []):
        result.append({'ticket_id': ticket.get('id'), 'tag': tag, 'sync': '123'})
    return result

print(list(map(transform, raw)))

But it's returning something like [[{...}], [{...}]] and the syntax looks strange.

What is the right approach to return something like:

[{'ticket_id': 1, 'tag': 'tag_a', 'sync': '123'}, {'ticket_id': 1, 'tag': 'tag_b', 'sync': '123'}, ...]
0

2 Answers 2

3

You just need to flatten your results. Essentially, you used a map operation when you wanted a flat-map operation.

You can do this in one go by using a nested list comprehension:

[x for ticket in raw for x in transform(ticket)]

Of course, you could have done something like:

[x for xs in map(transform, raw) for x in xs]

Or just a regular nested loop would work.

Sign up to request clarification or add additional context in comments.

Comments

2

This is one way to do it using nested for loops. Moreover, you don't need to map your function. You can just pass the list to the function and print. The problem with your code was that you were using a single for loop whereas, the depth (length) of your tags was more than one

raw = [{'id': 1, 'tags': ['tag_a', 'tag_b']}, {'id': 2, 'tags': ['tag_c', 'tag_b']}]

def transform(ticket):
    result = []
    for dic in raw:
        for tag in dic['tags']:
            result.append({'ticket_id': dic['id'], 'tag': tag, 'sync': '123'})
    return result

print(transform(raw))
# [{'ticket_id': 1, 'tag': 'tag_a', 'sync': '123'}, {'ticket_id': 1, 'tag': 'tag_b', 'sync': '123'}, 
#  {'ticket_id': 2, 'tag': 'tag_c', 'sync': '123'}, {'ticket_id': 2, 'tag': 'tag_b', 'sync': '123'}]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.