Geogrammer
Geogrammer

Reputation: 137

Python CSV - Writing from Two Dictionaries

I'm trying to create a script that will write a CSV file containing columns from two separate input files. I'm having an issue with trying to use csv.Dictreader() on both of the input files so that the columns in the file to be written can be easily referenced. Using print, it appears that keys from both dictionaries are being understood properly, but only the information from one Dictionary (which ever is placed first in the script) is being properly written, while the second will only write the very first value in each row.

An example of the input files:

file1.csv

A,B
1,2
3,4
5,6

file2.txt

1.11
2.22
3.33

The outputfile I'd like to create, with C in the first column, and A in the second:

output.csv

1.11     1
2.22     3
3.33     5

This is the code that I have thus far:

import csv

with open('file1.csv', 'rb') as FileOne:
    with open('file2.txt', 'rb') as FileTwo
        with open('output.csv', 'wb') as OutFile:
            LabelsOne = ['A', 'B']
            LabelsTwo = ['C']
            inf.next()
            DictOne = csv.DictReader(FileOne, LabelsOne, skipinitialspace=True)
            DictTwo = csv.DictReader(FileTwo, LabelsTwo, skipinitialspace=False)
            outf = csv.writer(OutFile, delimiter='\t')

            for DataOne in DictOne:
                for DataTwo in DictTwo:
                    DataOne.update(DataTwo)
                    outf.writerow([DataOne['C'], DataOne['A']])

But right now the ouput I'm getting is either

1.11     1
2.22     1
3.33     1

OR

1.11    1
1.11    3
1.11    5

Depending on if I put for DataOne in DictOne or for DataTwo in DictTwo first. I've looked through other discussions on the use of CSV Dictionaries but have not found anyone else with this issue. The keys from both dictionaries are defintiely being recognized, but only one is being written properly. Is it possible to write the output file using both dictionaries?

I know that it would usually be easier to just open up the CSV files and copy/paste columns to a new document, but I need this process to repeat over many files and as part of a batch.

Upvotes: 0

Views: 156

Answers (1)

Andrew Clark
Andrew Clark

Reputation: 208565

You don't want nested loops at all here, try using zip() instead:

            for DataOne, DataTwo in zip(DictOne, DictTwo):
                DataOne.update(DataTwo)
                outf.writerow([DataOne['C'], DataTwo['A']])

Upvotes: 1

Related Questions