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

Convert list of dictionaries to dictionary of dictionaries

I have a list of dictionaries

ls1 = [{'AccountBalance': '78', 'Status': '0'},
 {'AccountBalance': '56', 'Status': '1'},
 {'AccountBalance': '34', 'Status': '0'},
 {'AccountBalance': '12', 'Status': '0'}]

I would like to convert this to a dictionary of 2 dictionaries

dict1 = {'AccountBalance': {0: '78',
  1: '56',
  2: '34',
  3:  '12'},
    'Status': {0: '0',
  1: '1',
  2: '0',
  3: '0'}}

what would be the fastest way to do this?

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

pd.DataFrame(ls1).to_dict() works, but I want to know if something is a little faster?

>Solution :

A one-liner solution would be

dict1 = {key: {index: item[key] for index, item in enumerate(ls1)} for key in ls1[0]}
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