Search code examples
pythongspread

How do I return a range of cells in Google Sheets based on a condition, using Python?


Below is an example of what I have in a Google Sheet:

1   | ID | Fav Color | Fav Book |
2   | 01 |  color1   |  book2   |
3   | 02 |  color2   |  book2   |
4   | 03 |  color2   |  book1   |
...
100 | 99 |  color1   |  book2   |

Using gspread, is it possible to find & print the ID and favorite color of only the people that say book2 is their favorite book? (expected result: print rows 2, 3, and 100)

I've been looking through the gspread docs, and just can't think of anything. Any help is greatly appreciated.


Solution

  • Load the worksheet, and then load all data either as a:

    You can filter the list down using a list comprehension, or you could just loop over the entire dataset while printing and skip the rows where the favorite book isn't what you are looking for.

    This example uses get_all_records() followed by a list comprehension to filter the list, and then printing. I did not go to the trouble of setting up a test spreadsheet for testing so if I made an obvious errors please feel free to edit.

    import gspread
    
    # Load Spreadsheet and primary worksheet
    gc = gspread.service.account()
    sheet = gc.open('My Data')
    worksheet = sheet.sheet1 
    
    # Load as a list of dicts
    list_of_dicts = worksheet.get_all_records()
    
    # Strip people who don't like book2.
    book2_lovers = [d for d in list_of_dicts if d.get("Fav Book") == "book2"]
    
    # Print header
    print(f"{'ID':-^8}    {'Fav Color':-^15}")
    # Print data
    for person in book2_lovers:
        print(f"{person.get('ID'):^8}    {person.get('Fav Color'):^15}")