0

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.

3
  • What have you tried? This is not hard. x = [d['x'] for d in data]. Commented Jul 5, 2022 at 20:36
  • 1
    Do you really have quotes around each dictionary in the original list? Commented Jul 5, 2022 at 20:39
  • I already try this but there is quotation mark at each cell so it return an error message : TypeError: string indices must be integers. Not just next to the x, y and z. Commented Jul 5, 2022 at 20:51

2 Answers 2

1

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'])
Sign up to request clarification or add additional context in comments.

Comments

0

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.

3 Comments

There is quotation mark at each cell and this is my big difficulty. I try your code but it doesn't work, sadly.
In OP's data, each list item is actually wrapped with ', thus they are strings so cannot treat them like dicts.
Oh, seems like I missed those parts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.