Search code examples
pythongoogle-colaboratory

Read in multiple google sheet workbooks with a for loop in google colaboratory


I have multiple google workbooks all named in a structured way, e.g.:

Math_Student Assessment Sheet Grade 10 2021-2022

Math_Student Assessment Sheet Grade 9 2021-2022

I made a dic for all the workbook names and variables I would like to declare them as:

grade_dict = {'Grade K': 'grade_k',
'Grade 1': 'grade_1',
'Grade 2': 'grade_2',
'Grade 3': 'grade_3',
'Grade 4': 'grade_4',
'Grade 5': 'grade_5',
'Grade 6': 'grade_6',
'Grade 7': 'grade_7',
'Grade 8': 'grade_8',
'Grade 9': 'grade_9',
'Grade 10': 'grade_10'}

I tried to read them in:

for key, val in grade_dict:
  vars()['math_student_assessment_sheet_' + val + '_2021_2022'] = gc.open('Math_Student Assessment Sheet' + key + '2021-2022') 

But I get this error:

ValueError                                Traceback (most recent call last)
<ipython-input-20-ec7184dea63b> in <module>()
----> 6 for key, val in grade_dict:
      7   vars()['math_student_assessment_sheet' + val + '_2021_2022'] = gc.open('Math_Student Assessment Sheet' + key + '2021-2022')

ValueError: too many values to unpack (expected 2)

I am confused: what is wrong with my code?


Solution

  • You are iterating over dictionary. You will need .items() at the end for unpacking keys and values from dictionary. like

    for key, val in grade_dict.items():