Get specific key from multiple keys in python dictionary - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Get specific key from multiple keys in python dictionary (/thread-17015.html) |
Get specific key from multiple keys in python dictionary - pradeepkumarbe - Mar-24-2019 I have CSV like this(below is the sample) Month Seg Zone Dist SALES 2018-12 HIGH A-ZONE NY 200 2018-12 LOW A-ZONE NY 100 2018-12 MEDIUM A-ZONE NY 300 And So on.... Out of above csv file I have created sql operation like in python In SQL I would do like this SELECT Month,Seg,SUM(Sales) FROM CSV group by Month,Seg Same like I have created in python with open('/Sales.csv','r') as sixm_sales: ca_dict_reader = csv.DictReader(sixm_sales,delimiter='|') agg_6m = defaultdict(float) for row in ca_dict_reader: agg_6m[row["Month"],row["Seg"]] += float(row["Sales"]) print(agg_6m)Dict agg_6m which gives below output like this defaultdict(<class 'float'>, {('2018-12', 'HIGH'): 2945.17, ('2018-12', 'LOW'): 5064.99, ('2018-12', 'MEDIUM'): 5036.360000000001, ('2018-12', 'NON_TARGET'): 33.0, ('2018-11', 'HIGH'): 3719.67, ('2018-11', 'LOW'): 5029.84, ('2018-11', 'MEDIUM'): 4899.49, ('2018-11', 'NON_TARGET'): 36.0, ('2018-10', 'HIGH'): 4381.83, ('2018-10', 'LOW'): 4826.76, ('2018-10', 'MEDIUM'): 4762.869999999999, ('2018-10', 'NON_TARGET'): 32.0, ('2018-09', 'HIGH'): 2788.67, ('2018-09', 'LOW'): 4754.07, ('2018-09', 'MEDIUM'): 4803.16, ('2018-09', 'NON_TARGET'): 28.0, ('2018-08', 'HIGH'): 3915.5, ('2018-08', 'LOW'): 5220.99, ('2018-08', 'MEDIUM'): 5254.34, ('2018-08', 'NON_TARGET'): 36.0, ('2018-07', 'HIGH'): 4172.33, ('2018-07', 'LOW'): 4619.33, ('2018-07', 'MEDIUM'): 4516.65, ('2018-07', 'NON_TARGET'): 30.0})From this I am trying to create JSON like below "goal": { "title": "Six Month Sales", "value": 190, "percentage": "-5.0", "max": 9.84, "min": 2.23, "category": ["2018-07","2018-08","2018-09","2018-10","2018-11","2018-12"], "xaxistitle": "Month", "yaxistitle": "Sales", "series": [ { "Name": "MEDIUM", "data": [3,4,6.11,4.19,8.96,6.08,2.23] } } From agg_6m dictionary I have to create JSON output like above where Month will go in Category , Seg in name and sales in data. How this can be done? |