Home > Mobile >  How can I take the first values from a list of dictionaries and create another list with it?
How can I take the first values from a list of dictionaries and create another list with it?

Time:11-10

I am very new to python and machine learning and i searched for this specific question but could not find something useful. I have a list:

data=[{'a':1,
        'b':2},
        {'a':3,
         'b':4}]

I want a separate list for a and b with their values. For example:

a=[1,3] 
b=[2,4]

I tried to do:

a=[lst['a'] for lst in data] 
b=[lst['b'] for lst in data]

but the elements in a and b become a string?For example, i can not multiply a[0] and b[1]. I'd be so glad to hear if anyone has a solution for this or any advice to do something better. Sorry if I could not explain more clearly, like I said I am very new to all of this and I do not know the terminology etc. whatsoever. Thank you in advance!

CodePudding user response:

If you have a list of dicts, with identical keys, then in that case you could use the the library called Pandas and its DataFrames, which essentially is a Matrix. If you're working with machine learning you'll most likely use this library quite a lot anyways. But then you can select a specific column.

import pandas as pd

df = pd.DataFrame(list)

    x1  x2  x3
0   1   2   3
1   1   2   3
2   1   2   3

If you now want the select all values for x1, simply do

x1_values = df["x1"] # returns [1, 1, 1]

To get the product of each row, you can do this:

df.prod(axis=1) # returns [6, 6, 6]

The you get product for the whole row, however many rows you might should have

  • Related