How to append row to specific columns with gspread?

47 Views Asked by At

I have a google sheet with values on it. Think it like this:

header1 col1 header 3 col2
First row
Second row

I will have another data that will come and fill the 2nd and 4th column by respectively.

So what I want to use append_row with specific column name because after each process (my code) I want to immediately add it to my google sheet.


WHAT I DO FOR NOW (I want to change this logic):

I have 2 columns like this. So what I have done before after my code completes (all data is ready now) I was adding those data with worksheet update like this (I am using gspread):

        headers = worksheet.row_values(1)
        col1_index = headers.index('col1') + 1
        col2_index = headers.index('col2') + 1



        for item in result:
            col1_list.append(item['col1'])
            col2_list.append(item['col2'])
            

        col1_transposed = [[item] for item in col1_list]
        col2_transposed = [[item] for item in col2_list]


        col1_range = '{}2:{}{}'.format(chr(65 + col1_index - 1), chr(65 + col1_index - 1),
                                                len(col1_list) + 1)

        col2_range = '{}2:{}{}'.format(chr(65 + col2_index - 1), chr(65 + col2_index - 1),
                                                len(col2_list) + 1)


        worksheet.update(col1_range, col1_transposed)
        worksheet.update(col2_range, col2_transposed)

But now I want to say like I want to append my data row by row to specific columns. After each process I will have a data like this

{'col1': 'value1', 'col2': 'value2'}

and value1 will be on the col1 column and value2 will be on the col2 column in the first row.

After I will have the same thing from the code:

{'col1': 'value3', 'col2': 'value4'}

The result I would like to see:

header1 col1 header 3 col2
First value1 row value2
Second value 3 row value4
0

There are 0 best solutions below