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

How to read values from SQL into a dict of lis

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,

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

{ 
'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 , 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]},
]
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