1

I would like to make the first column of each row in an excel spreadsheet as a key and rest of the values in that row as its value so that I can store them in a dictionary. The problem is, when I loop through the rows and columns all the row values are getting stored in every key.

import openpyxl

from openpyxl import load_workbook

file = "test.xlsx"

#load the work book
wb_obj = load_workbook(filename = file)

wsheet = wb_obj['test']

#dictionary to store data
dataDict = {}

value = []

row_count = wsheet.max_row
col_count = wsheet.max_column

# loop to get row and column values
for i in range(2, row_count+1):
    for j in range(i, col_count+1):
        key   = wsheet.cell(row=i, column=1).value
        print (key)
        value.append(wsheet.cell(row=i, column=j).value)
        print (value)

    dataDict[key] = value

#prompt user for input
userInput = input("Please enter an id to find a person's details: ")

print (dataDict.get(int(userInput)))

data in spreadsheet: enter image description here

Result I'm expecting: {1: ['John', 'Doe', 4567891234, '[email protected]'], 2: ['Wayne 'Kane', 1234567891, '[email protected]']}

Result I got: {1: ['John', 'Doe', 4567891234, '[email protected]', 'Kane', 1234567891, '[email protected]'], 2: ['John', 'Doe', 4567891234, '[email protected]', 'Kane', 1234567891, '[email protected]']}

1 Answer 1

8

Openpyxl already has a proper way to iterate through rows using worksheet.iter_rows(). You can use it to unpack the first cell's value as the key and the values from the other cells as the list in the dictionary, repeating for every row.

from openpyxl import load_workbook

file = "test.xlsx" #load the work book
wb_obj = load_workbook(filename = file)
wsheet = wb_obj['test']
dataDict = {}

for key, *values in wsheet.iter_rows():
    dataDict[key.value] = [v.value for v in values]
3
  • 1
    How to omit first row in excel from this loop if we have names for columns like id, first name, last name, phone, etc
    – BTK
    Commented Mar 24, 2019 at 1:34
  • 3
    Use the keyword argument min_row to specify from which row to start iterating: wsheet.iter_rows(min_row=2).
    – jfaccioni
    Commented Mar 24, 2019 at 12:20
  • This openpyxl library hasn't been updated since 2015 Commented Sep 21, 2021 at 15:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.