Parsing Data from a Google Spreadsheet on Google Colab

I have successfully printed google spreadsheet data using python on google colaboratory:

  1. created project and generated json key for google doc app
  2. mounted google drive to google colab
  3. import spread via !pip install gspread google-auth
  4. printed the data from a google spreadsheet using JSON API key permissions from Google Cloud Platform

Next, I want to parse the data by forming a dictionary of characters and their associated coordinates: x,y. However, after printing the data from the spreadsheet successfully I failed to understand how to parse the data from gspread into a character dictionary. I used the following python code:

Preformatted text

def fetch_google_doc_data_google_doc_data(doc_url):
    """

    Fetch data from a Google Sheet.
    Assumes the document contains a table of characters and its coordinates. 
    """
    # Open the document by its URL
    sh = client.open_by_url("https://docs.google.com/spreadsheets/d/1PhcQxtYIbabosVLp-SsPz4YfXM_NMoDv35H-1vkIaD4/")
 
    # Get the first worksheet
    sh = sheet.get_worksheet(0)

    # Get all data from the worksheet
worksheet = sh.get_worksheet(0)
print(worksheet.get_all_values())

def parse_data(data):
    """
    Parses the data into a dictionary mapping coordinates to Characters.
    """
    char_dict = {}
    # Parse each row in the data
    for row in data[1:]:  # Skip the header row
        try:
            # Assume each row is formatted as [Character, x, y]
            char, x_strand, y_strand = row
            x = int(x_strand)
            y = int(y_strand)
            char_dict[(x,y)] = char
        except ValueError:
            # Skip rows that don't match the expected format
            pass
    return char_dict

The code printed the entire spreadsheet data but the empty character dictionary fails to populate. Do I need to define data in parse the data segment of the code? i.e. def parse_data(data):

I don’t see a call to parse_data in your code - just the function definition. Are you calling it somewhere else that you didn’t share?

Thank you for answering my question and catching my error.
You’re right I have not included a call to parse_data in my code.
Can you please offer guidance on how / where to include a call to ‘parse_data’ in my code? Do I define rows and column spans?

That’s more specific to your work flow and business logic. TBH I’ve never tried to use Google Sheets in Python so I can’t offer any great advice there.