0

I have a list with dictionary inside, with the following keys: id, external_id_client, product_id, as below:

[{'id': 3, 'external_id_client': '7298', 'product_id': 13}, 
{'id': 3, 'external_id_client': '7298', 'product_id': 8}, 
{'id': 4, 'external_id_client': '3', 'product_id': 12}, 
{'id': 4, 'external_id_client': '3', 'product_id': 9}, 
{'id': 5, 'external_id_client': '4', 'product_id': 12}]

I need that if the ID and external_id are repeated and I have information in the product_id key it creates a tuple in the product_id.

Expected output:

[{'id': 3, 'external_id_client': '7298', 'product_id': (13, 8)}, 
{'id': 4, 'external_id_client': '3', 'product_id': (12, 9)}, 
{'id': 5, 'external_id_client': '4', 'product_id': (12)}]

How can I do this?

1 Answer 1

2

You can use itertools.groupby for this:

from itertools import groupby

lst = [
    {'id': 3, 'external_id_client': '7298', 'product_id': 13}, 
    {'id': 3, 'external_id_client': '7298', 'product_id': 8}, 
    {'id': 4, 'external_id_client': '3', 'product_id': 12}, 
    {'id': 4, 'external_id_client': '3', 'product_id': 9}, 
    {'id': 5, 'external_id_client': '4', 'product_id': 12}
]

result = [
    {
        "id": itemid, 
        "external_id_client": client,
        "product_id": tuple(item["product_id"] for item in group)
    }
    for (itemid, client), group 
        in groupby(lst, key = lambda item: (item["id"], item["external_id_client"]))
]
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect! The only problem is that when it only has a number it has a comma at the end, for example: (9,), is there a way to fix this?
This is just a notation in the output. A tuple with one member is always encoded like that to make the difference with just a parenthesed expression. It's python syntax.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.