I am working on parsing an orders.csv file with products and prices by different vendors which is kind of a time-series data.
The output of that process looks something like below, with order total by product and vendor -
source_dict = {
'amazon': {'macbookpro': {'total': 1200}, 'ps5': {'total': 600}},
'walmart': {'ps5': {'total': 750}},
'walgreens': {'sonyheadset': {'total': 900}}
}
I need to write this data to another csv file in descending order by total. I am able to sort the items by total, but needs a new dictionary to store the sorted order -
new_dict = {}
for domain, products in source_dict.items():
for product in products:
total = products[product]['total']
new_dict[domain+product] = {'source': domain, 'product': product, 'total': total}
sorted_items = sorted(new_dict.values(), key=lambda x: x["total"], reverse=True)
for item in sorted_items:
print(f"{item['source']},{item['product']},{item['total']}")
In the above code I am basically using two different temporary objects "new_dict", "sorted_items" to store and sort the data items.
Can I simply sort the "source_dict" by "total" eliminating "new_dict"?
Any suggestions are highly appreciated.
Best,
Sri