pythondictionarygspreadtext-search

gspread: Is there a way to load a dict into sheet.update_cells()?


I have what I think is extremely sloppy code here:

industry = []
headquarters = []
specialties = []
totalEmployeeCount = []
growth6Mth = []
website = []

for i in cvs_data:
    j = ci_data[0]
    for j in ci_data:
        if i['companyName'] == j['name']:
            industry.append(Cell(row = cvs_data.index(i)+2, col = 6,
                             value = j['industry']))
            headquarters.append(Cell(row = cvs_data.index(i)+2, col = 8,
                             value = j['headquarters']))
            specialties.append(Cell(row = cvs_data.index(i)+2, col = 9,
                             value = j['specialties']))
            totalEmployeeCount.append(Cell(row = cvs_data.index(i)+2, col = 10,
                             value = j['totalEmployeeCount']))
            growth6Mth.append(Cell(row = cvs_data.index(i)+2, col = 11,
                             value = j['growth6Mth']))
            website.append(Cell(row = cvs_data.index(i)+2, col = 14,
                             value = j['website']))
            
cvs.update_cells(industry)
cvs.update_cells(headquarters)
cvs.update_cells(specialties)
cvs.update_cells(totalEmployeeCount)
cvs.update_cells(growth6Mth)
cvs.update_cells(website)

Where cvs_data is a list of dicts that is used for its index. The actual gspread worksheet (cvs) will be updated with values from ci_data, another list of dicts.

I'm guessing my search could be better too.

Is it possible to append all those values (i.e. industry, headquarters, etc.) into one dictionary instead of individual lists, then call update_cells() on that one dictionary?


Solution

  • If your goal is to have one update_cells(), then you should be able to use:

    cvs.update_cells(industry + headquarters + specialties + ...)
    

    Your Cell objects look like they all have row and column data, so they don't need to be in separate lists.

    I don't think I've seen anything that goes from a dict to a google sheet, but another way to do that (where the keys are industry, headquarters, etc. while the values are the list of Cells) would be:

    all_data = {'industry': [], 'headquarters': [], ...}
    # add cells to all_data
    data = []
    for list_of_cells in all_data.values():
        data.extend(list_of_cells)
    cvs.update_cells(data)
    

    For your searching, reorganizing ci_data from a list of dicts to one dict might help. You can have the keys be the names while the values are the dicts:

    ci_data_dict = dict()
    for item in ci_data:
        name = item['name']
        ci_data_dict[name] = item
    

    Then you won't have nesting for loops in your code:

    for i in cvs_data:
        j = ci_data_dict[i['company_name']]
        industry.append(Cell(row = cvs_data.index(i) + 2, col = 6, value = j['industry']))