user12154400
user12154400

Reputation:

CSV writing - split rows into multiple columns

Sorry if this question is repeated but I searched and could not find a simple example.

I'm trying to write dictionary values to csv file. Here is python code:

w = csv.writer(open("../log.csv", "w"))
alphanum = {'A':1, 'B':2, 'C':3, 'D':4, 'ZA':27, 'ZB':28, 'ZC':29, 'ZD':30}
for key, val in sorted (alphanum.items()):
  w.writerow([key, val])

Here is the output in the csv file:

|---------|---------|
|    A    |     1   |
|    B    |     2   |
|    C    |     3   |
|    D    |     4   |
|    ZA   |     27  |
|    ZB   |     28  |
|    ZC   |     29  |
|    ZD   |     30  |
|---------|---------|

But I want to split the rows and write in the following format:

|---------|---------|---------|---------|
|    A    |    1    |    ZA   |    27   |
|    B    |    2    |    ZB   |    28   |
|    C    |    3    |    ZC   |    29   |
|    D    |    4    |    ZD   |    30   |
|---------|---------|---------|---------|

Upvotes: 1

Views: 817

Answers (1)

Epion
Epion

Reputation: 518

EDIT

After additional clarification, here is the solution that you were looking for:

import csv

w = csv.writer(open("../log.csv", "w"))
alphanum = {'A':1, 'B':2, 'C':3, 'D':4, 'ZA':27, 'ZB':28, 'ZC':29, 'ZD':30}
alphanum_size = len(alphanum)  
sorted_alphanum = sorted(alphanum.items())
for i in range(int(alphanum_size / 2)):
    w.writerow(sorted_alphanum[i] + sorted_alphanum[i + 4]) if i + 4 < alphanum_size else w.writerow(sorted_alphanum[i])
# Corner case - size is odd and len != 0, write last k: v pair
if alphanum_size % 2 and alphanum_size:  
    w.writerow(sorted_alphanum[-1])

AS you can see, we are assigning size of the dictionary to a variable alphanum_size, to avoid excessive len() function calls in the for loop, which would hinder efficiency somewhat.

We have also used a ternary operator in the for loop. It is equivalent to:

if i + 4 < alphanum_size:
    w.writerow(sorted_alphanum[i] + sorted_alphanum[i + 4])
else:
    w.writerow(sorted_alphanum[i]

The easiest way would be to change your data container, and basically turn it into a list of dicts.

w = open("../log.csv", "w")
alphanum = [{'col1': 'A', 'col2': 1, 'col3': 'ZA', 'col4': 27},
            {'col1': 'B', 'col2': 2, 'col3': 'ZB', 'col4': 28},
            ...]

Then, you can perform the write operation easily with a DictWriter.

header_columns = alphanum[0].keys()
writer = csv.DictWriter(w, header_columns)
writer.writeheader()
writer.writerows(alphanum)

An additional improvement that could be done here is to use a context manager instead of a regular file open(). You can read up on those here.

Upvotes: 1

Related Questions