Writing into a .csv file

Question:

I have an array and some code that gets rid of duplicate names, along with their previous three values.

file = ['Sorin,0,0,0', 'Sorin,0,1,0', 'David,0,0,0', 'Sorin,0,0,0', 'Sorin,0,0,0']
['Sorin', '0', '0', '0']
import json
Dict = {}

for line in file:
  line = line.split(",")
  key, value = line[0], line[1:]
  Dict[key] = value

Zip = list(zip(Dict.keys(), Dict.values()))

with open("Class1.csv","w",newline="") as f:
    writer = csv.writer(f)
    writer.writerows(Zip)

I am trying to write the array back into the .csv file but I am getting an issue. I am quite new to writing in .csv so I’m sorry.

print(Zip)
#Output
[('Sorin', ['0', '0', '0']), ('David', ['0', '0', '0'])]

The issue is when I try to write it into the .csv file.
It writes the values in the columns incorrectlyas:

……A…………..B

1…Sorin..[0,0,0]

2…David..[0,0,0]

I want it to be written as:

……….A……..B…C…D

1…Sorin…..0…0…0

2…David….0…0…0

Asked By: niub

||

Answers:

I think… the issue is in list "Zip"… Try this code, where in Zip list, each both keys & values from dict will be individual list…

file = ['Sorin,0,0,0', 'Sorin,0,1,0', 'David,0,0,0', 'Sorin,0,0,0', 'Sorin,0,0,0']

import csv
Dict = {}

for line in file:
  line = line.split(",")
  key, value = line[0], line[1:]
  Dict[key] = value

Zip = [["A","B","C","D"]] # Create empty list as Zip = [] if you don't want A,B,C,D as columns
for k,v in Dict.items():
    Zip.append([k]+v)

with open("Class1.csv","w",newline="") as f:
    writer = csv.writer(f)
    writer.writerows(Zip)

enter image description here

Answered By: Sachin Kohli
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.