-1

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.

yes
  • 3
  • 2

1 Answers1

0

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}")
nigh_anxiety
  • 1,428
  • 2
  • 4
  • 12
  • Awesome, thanks for your help! If I may ask, what do ^8 and ^15 mean? – yes May 12 '23 at 18:43
  • In an f-string, the info after the : is for formatting, where you can put a fill character (default is a space), justification (`<` for left justication, `^` for center justication, or `>` for right justification, and the number is how many spaces to fill. So `f"{value:^8}"` means to take the value and center over a space of 8 characters, using spaces to fill. Here I just used it to sort of make columns for your output. For example, `f"{'ID':-^8}"` results in `---ID---` – nigh_anxiety May 12 '23 at 21:40