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

Separate list of objects in Python

I need to separate a list of objects in Python but I don’t know how to do and don’t found the solution.

My list is 244 cells of data like that :

{'x':-9.717017,'y':-14.0228567,'z':145.401215} 

and I want, as a result, 3 lists with all the ‘x’, all the ‘y’ and all the ‘z’.
The original list is express as :

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

['{'x':-9.717017,'y':-14.0228567,'z':145.401215}', ... , '{'x':-6.44751644,'y':-65.20397,'z':-67.7079239}']. 

Thanks a lot.

>Solution :

Loop over the list, and call ast.literal_eval() to convert each string to a dictionary. Then append each item in the dictionary to the appropriate list.

import ast

x_list = []
y_list = []
z_list = []
for item in data:
    d = ast.literal_eval(item)
    x_list.append(d['x'])
    y_list.append(d['y'])
    z_list.append(d['z'])
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