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

Add list as keys for another list and convert to dictionary

I have a list of columns and records that I get by using DATA-API RDS execute_statement using boto3. As the way the api responds it difficult to get the data out in a psycopg2 RealDictCursor format to insert into another database.
What I want to do is illustrated below.

columns = ["a","b","c"]
records = [[1,2,3],[4,5,6]] 

I want to convert this to a dictionary that represents it like

[{"a":1,"b":2,"c":3},{"a":4,"b":5,"c":6}]

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

>Solution :

Do it like this:

Python 3.8.9 (default, Aug  3 2021, 19:21:54) 
[Clang 13.0.0 (clang-1300.0.29.3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> columns = ["a","b","c"]
>>> records = [[1,2,3],[4,5,6]] 
>>> [dict((a,b) for a,b in zip(columns,rec)) for rec in records]
[{'a': 1, 'b': 2, 'c': 3}, {'a': 4, 'b': 5, 'c': 6}]
>>> 
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