I am having the following problem.
class Inventory:
def __init__(self,project_no,country,category,product,count):
self.project_no = project_no
self.country = country
self.category = category
self.product = product
self.count = count
inventory_list = []
inventory_list.append(Inventory(1,'USA','Beverages','Milk',2))
inventory_list.append(Inventory(1,'USA','Beverages','Juice',5))
inventory_list.append(Inventory(1,'USA','Snacks','Potato Chips',2))
inventory_list.append(Inventory(1,'USA','Oils','Canola',5))
inventory_list.append(Inventory(1,'USA','Oils','Olive',8))
inventory_list.append(Inventory(1,'CAN','Beverages','Milk',7))
inventory_list.append(Inventory(1,'CAN','Beverages','Juice',8))
inventory_list.append(Inventory(1,'CAN','Snacks','Potato Chips',8))
inventory_list.append(Inventory(1,'CAN','Oils','Canola',3))
inventory_list.append(Inventory(1,'CAN','Oils','Olive',4))
{'Inventory': [{'Country': inv.country , 'Category' : [{inv.category : [{'Product' : inv.product}]}] } for inv in inventory_list]}
This code is giving me the following output.
{'Inventory': [{'Country': 'USA', 'Category': [{'Beverages': [{'Product': 'Milk'}]}]}, {'Country': 'USA', 'Category': [{'Beverages': [{'Product': 'Juice'}]}]}, {'Country': 'USA', 'Category': [{'Snacks': [{'Product': 'Potato Chips'}]}]}, {'Country': 'USA', 'Category': [{'Oils': [{'Product': 'Canola'}]}]}, {'Country': 'USA', 'Category': [{'Oils': [{'Product': 'Olive'}]}]}, {'Country': 'CAN', 'Category': [{'Beverages': [{'Product': 'Milk'}]}]}, {'Country': 'CAN', 'Category': [{'Beverages': [{'Product': 'Juice'}]}]}, {'Country': 'CAN', 'Category': [{'Snacks': [{'Product': 'Potato Chips'}]}]}, {'Country': 'CAN', 'Category': [{'Oils': [{'Product': 'Canola'}]}]}, {'Country': 'CAN', 'Category': [{'Oils': [{'Product': 'Olive'}]}]}]}
What I actually need is more like below.
{ "Inventory": [{ "country": "USA", "category": [{ "Beverages": [{ "product": "Milk", "count": 2 }, { "product": "Juice", "count": 5 }] }, { "Snacks": [{ "product": "Potato Chips", "count": 2 }] }, { "Oils": [{ "product": "Canola", "count": 5 }, { "product": "Olive", "count": 8 }] }] }, { "country": "CAN", "category": [{ "Beverages": [{ "product": "Milk", "count": 7 }, { "product": "Juice", "count": 8 }] }, { "Snacks": [{ "product": "Potato Chips", "count": 8 }] }, { "Oils": [{ "product": "Canola", "count": 3 }, { "product": "Olive", "count": 4 }] }] } ] }
How to do this? I thought list comprehension is the way to go. But I am having trouble beyond this point. I thought this should be really easy for a python coder. With my limited python I could only reach this far. If anyone can help.