PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 28, 2022

[FIXED] How to make columns as row using dict & map

 August 28, 2022     csv, csvreader, dictionary, python     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing