creating a list of dictionaries from pandas dataframe

This is my df:

df = pd.DataFrame({'sym': ['a', 'b', 'c', 'x', 'y', 'z', 'q', 'w', 'e'],
                   'sym_t': ['tsla', 'msft', 'f', 'aapl', 'aa', 'gg', 'amd', 'ba', 'c']})

I want to separate this df into groups of three and create a list of dictionaries:

options = [{'value':'a b c', 'label':'tsla msft f'}, {'value':'x y z', 'label':'aapl aa gg'}, {'value':'q w e', 'label':'amd ba c'}]

How can I create that list? My original df has over 1000 rows.

1 answer

  • answered 2021-10-12 15:53 Quang Hoang

    Try groupby to concatenate the rows, then to_dict:

    tmp = df.groupby(np.arange(len(df))//3).agg(' '.join)
    tmp.columns = ['value', 'label']
    tmp.to_dict(orient='records')
    

    Output:

    [{'value': 'a b c', 'label': 'tsla msft f'},
     {'value': 'x y z', 'label': 'aapl aa gg'},
     {'value': 'q w e', 'label': 'amd ba c'}]
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum