I am reading values from SQL server using pymssql library using the below code
df = pd.read_sql_query(query, cnxn)
This is giving me a df as below
addr port device_id
==============================
XXX 1001 01
XXX 1001 02
XXX 1001 03
YYY 1001 04
YYY 1001 05
Is there a way to convert this df into a dict of list as shown below,
{
'addr': [XXX, XXX, XXX],
'port': [1001,1001,1001],
'device_id': [01, 02, 03]
},
{
'addr': [YYY,YYY],
'port': [1001,1001],
'device_id': [04, 05]
}
Thanks,
>Solution :
Assuming pandas, you can use groupby.apply and to_dict:
out = df.groupby('addr').apply(lambda g: g.to_dict('list')).to_list()
Output:
[{'addr': ['XXX', 'XXX', 'XXX'],
'port': [1001, 1001, 1001],
'device_id': [1, 2, 3]},
{'addr': ['YYY', 'YYY'],
'port': [1001, 1001],
'device_id': [4, 5]},
]