Issue
My csv file:
Measure names,Measure values
State,CA
Audit,Y
WFH,Y
State,MN
Audit,N
WFH,N
State,SC
Audit,Y
WFH,Y
State,LA
Audit,N
WFH,N
State,CO
Audit,P
WFH,N
State,MO
Audit,Y
WFH,N
State,NY
Audit,N
WFH,Y
Expected output :
State,Audit,WFH
CA,Y,Y
MN,N,N
SC,Y,Y
LA,N,N
CO,P,N
MO,Y,N
NY,N,Y
I dont want to use any extra library. I want to use only default python package.
code copied from stack over flow:
with open(r"input.csv") as in_f:
open(r"output.csv", "w", newline="") as out_f:
reader = DictReader(in_f)
writer = None
for items in reader:
row = {
**dict(map(itemgetter("Measure names", "Measure values"), items))
}
if not writer:
writer = DictWriter(out_f, row)
writer.writeheader()
writer.writerow(row)
Is that anything posssible using Dict,map and itemgetter. Request your help
Solution
Something like this?:
import csv
from itertools import islice
with open("in.csv", "r", newline="") as in_file:
reader = csv.DictReader(in_file)
fieldnames = ["State", "Audit", "WFH"]
values = (row["Measure values"] for row in reader)
with open("out.csv", "w", newline="") as out_file:
writer = csv.DictWriter(out_file, fieldnames=fieldnames)
writer.writeheader()
while slc := tuple(islice(values, 3)):
row = dict(zip(fieldnames, slc))
writer.writerow(row)
Answered By - Paul M. Answer Checked By - Candace Johnson (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.