Skip to content

Commit d4c3c03

Browse files
committed
Tidy up of to_dict and transpose code
1 parent d8b7bf5 commit d4c3c03

File tree

1 file changed

+7
-27
lines changed

1 file changed

+7
-27
lines changed

src/pytest_bdd/gherkin_parser.py

Lines changed: 7 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -130,25 +130,12 @@ def from_dict(cls, data: dict[str, Any]) -> Self:
130130

131131
def transpose(self) -> DataTable:
132132
# Transpose the cells, turning rows into columns
133-
134-
# Get the list of lists of cell values (i.e., extract all row cells)
135133
cells_matrix = [row.cells for row in self.rows]
136134

137-
# Check the maximum number of columns (to handle different row lengths)
138-
max_columns = max(len(row) for row in cells_matrix)
139-
140-
# Create a list to store the transposed cells
141-
transposed_cells = []
142-
143-
for col_idx in range(max_columns):
144-
# Create a new list for each transposed column
145-
transposed_column = []
146-
for row in cells_matrix:
147-
transposed_column.append(row[col_idx])
148-
149-
# Create a new row from the transposed column
150-
transposed_row = Row(id=str(col_idx), location=self.location, cells=transposed_column)
151-
transposed_cells.append(transposed_row)
135+
# Use zip to transpose the matrix and create transposed rows
136+
transposed_cells = [
137+
Row(id=str(i), location=self.location, cells=list(col)) for i, col in enumerate(zip(*cells_matrix))
138+
]
152139

153140
# Return a new DataTable with transposed rows
154141
return DataTable(location=self.location, rows=transposed_cells)
@@ -158,19 +145,12 @@ def to_dict(self) -> dict[str, list[str]]:
158145
if len(self.rows) < 2:
159146
raise ValueError("DataTable needs at least two rows: one for headers and one for values")
160147

161-
# Extract the header row (first row)
148+
# Extract the header row and the value rows
162149
header = [cell.value for cell in self.rows[0].cells]
163-
164-
# Extract the values from subsequent rows
165150
values_rows = [[cell.value for cell in row.cells] for row in self.rows[1:]]
166151

167-
# Transpose the values so that each column corresponds to a header key
168-
transposed_values = list(zip(*values_rows))
169-
170-
# Map each header to the corresponding list of values
171-
result_dict = {header[i]: list(transposed_values[i]) for i in range(len(header))}
172-
173-
return result_dict
152+
# Transpose values and map headers to columns
153+
return {key: list(values) for key, values in zip(header, zip(*values_rows))}
174154

175155

176156
@dataclass

0 commit comments

Comments
 (0)