[FIXED] Transfer the same values ​in the dictionary to another dictionary and save database

Issue

This is how orders are kept in the dictionary.

I want to keep the same seller values ​​in the dictionary in another dictionary. and separately I want to save it as order in database.

Orders:

{
    "1": {"image": "67021f123f31ab63834f.jpg", "name": "Chai", "price": 18.0, "quantity": "1", "seller": "2"}, 
    "24": {"image": "", "name": "Guaran\u00e1 Fant\u00e1stica", "price": 4.5, "quantity": "1", "seller": "2"}, 
    "3": {"image": "", "name": "Aniseed Syrup", "price": 10.0, "quantity": "1", "seller": "10"}
}

If the seller values ​​are the same, I want it to be like this.

{
    "1": {"image": "67021f123f31ab63834f.jpg", "name": "Chai", "price": 18.0, "quantity": "1", "seller": "2"}, 
    "24": {"image": "", "name": "Guaran\u00e1 Fant\u00e1stica", "price": 4.5, "quantity": "1", "seller": "2"}
}

{
    "3": {"image": "", "name": "Aniseed Syrup", "price": 10.0, "quantity": "1", "seller": "10"}
}

how can i separate dictionaries like this..

i am new here. Sorry for my language mistakes and other mistakes.

Solution

Create a dictionary whose keys are sellers, and values are these nested dictionaries.

from collections import defaultdict

sellers = default_dict(dict)

for orderid, order in orders.items():
    sellers[order['seller']][orderid] = order

Answered By – Barmar

Answer Checked By – Mildred Charles (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published