Home > other >  Separate list of objects in Python
Separate list of objects in Python

Time:07-06

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 :

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

Thanks a lot.

CodePudding user response:

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'])

CodePudding user response:

You can return the 'x', 'y', 'z' components while iterating over your list of dict() elements.

E.g.,

data = [{'x':-9.717017,'y':-14.0228567,'z':145.401215}, {'x':-9.717017,'y':-14.0228567,'z':145.401215}]

x = [d['x'] for d in data]
y = [d['y'] for d in data]
z = [d['z'] for d in data]

This should return the individual lists in x, y, and z respectively.

  • Related