Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extract values from list with dicts

I have a list with orders. Each order contains products and their prices.
What I want is to write the shortest script possible to count total number of products sold and total amount of money earned. I’m looking for fields "count" and "total".

[
   {
      "id":1,
      "items":[
         {
            "offerName":"name_1",
            "count":6,
            "prices":[
               {
                  "costPerItem":129.0,
                  "total":774.0
               }
            ]
         },
         {
            "offerName":"name_2",
            "count":1,
            "prices":[
               {
                  "costPerItem":120.0,
                  "total":120.0
               }
            ]
         }
      ]
   },
   {
      "id":2,
      "items":[
         {
            "offerName":"name_3",
            "count":10,
            "prices":[
               {
                  "costPerItem":30.0,
                  "total":300.0
               }
            ]
         },
         {
            "offerName":"name_4",
            "count":1,
            "prices":[
               {
                  "costPerItem":10.0,
                  "total":10.0
               }
            ]
         }
      ]
   }
]

I got the right values, but I think there is a way to make the calculation more beautiful, without a lot of looping.

counts = []
prices = []
for order in sales_data:
    products_list = order.get("items", [])
    for offer in products_list:
        counts.append(offer.get("count", 0))
        prices.append(offer.get("prices", []))
total_earned=[]
for price in prices:
    total = price[0].get("total", 0)
    total_earned.append(total)

print(sum(counts))
print(sum(total_earned))

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

For making the code as brief as possible, list comprehensions can be used.

I have come up with a solution with only 2 lines of logic.

I have defined the initial count and price as zero, and using list comprehension, I am updating the count and price for each item every iteration using the assignment operator :=

sales_data = [
    {
        "id": 1,
        "items": [
            {
                "offerName": "name_1",
                "count": 6,
                "prices": [
                    {
                        "costPerItem": 129,
                        "total": 774
                    }
                ]
            },
            {
                "offerName": "name_2",
                "count": 1,
                "prices": [
                    {
                        "costPerItem": 120,
                        "total": 120
                    }
                ]
            }
        ]
    },
    {
        "id": 2,
        "items": [
            {
                "offerName": "name_3",
                "count": 10,
                "prices": [
                    {
                        "costPerItem": 30,
                        "total": 300
                    }
                ]
            },
            {
                "offerName": "name_4",
                "count": 1,
                "prices": [
                    {
                        "costPerItem": 10,
                        "total": 10
                    }
                ]
            }
        ]
    }
]


count, prices = 0, 0
[(count:=count+item['count'], prices:=prices+item['prices'][0]['total']) for sale in sales_data for item in sale['items']]

print('Count:', count, ', Prices:', prices)

This code outputs

Count: 18 , Prices: 1204
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading