Home > front end >  How to assign a new variable for each cell in a row in Excel? (openpyxl)
How to assign a new variable for each cell in a row in Excel? (openpyxl)

Time:01-07

I am trying to iterate through a specific range of rows in a specific column and assign each row's cell data to a variable. I have a for loop for getting the specific row and column and then a for loop to get each cell's data and then a third for loop to assign the variable to each cell.

The issue I am having is combing the for loop that iterates through the cells and the for loop that creates new variables. Right now the last for loop just keeps assigning the last row's cell to each new variable and not all the rows to their appropriate variable.

I know its because the loop is within the other loop and that's why its getting stuck so how do I get this to work the way I want it to?

My code is below as follows:

# Iterates through rows in the MAC Address column
for row in ws.iter_rows(min_row=13, min_col=8, max_row=33, max_col=8):
    for cell in row:

        #Creates a dictionary to assign a variable for each cell
        d = {}

        #This loop is supposed to assign a new variable for each cell's value
        for i in range(1,14):  # for looping
            d["mac{0}".format(i)] = cell.value

This outputs predictably with only one row's cell but it is creating new variables (or keys for every value if you will):

{'mac1': '00:00:00:00:00:00', 'mac2': '00:00:00:00:00:00', 'mac3': '00:00:00:00:00:00'

CodePudding user response:

Are you trying to obtain something like this;
Note the dictionary is initialised outside the loop.

d = {}
for enum, row in enumerate(ws.iter_rows(min_row=13, min_col=8, max_row=33, max_col=8),1):
    k = f'mac{enum}'
    v = row[0].value
    d[k] = v

Dictionary will contain

mac1 = <row 13 col 8 value>
mac2 = <row 14 col 8 value>
mac3 = <row 15 col 8 value>
mac4 = <row 16 col 8 value>
....
  • Related