hsayya
hsayya

Reputation: 131

How to write two dictionaries to CSV?

I was wondering how I could iterate over two dictionaries: yin and BL.

I have the following code so far to iterate over yin only:

with open('output.csv', 'wb') as output:
  writer = csv.writer(output)
  for key, value in yin.iteritems():
    writer.writerow([key, value])

yin has values in a dictionary:

{'a': 2248433.0, 'b': 280955.0, 'c': 0.0}

BL has values in a dictionary:

{'a': 27.2, 'b': 57.6, 'c': 0.0}

I want to save it to an excel file so it looks like:

a  2248433.0    27.2     
b  280955.0     57.6   
c  0.0           0.0

Should I do the following?

with open('output.csv', 'wb') as output:
  writer = csv.writer(output)
  for key, value, valye in yin.iteritems(), BL.iteritems:
    writer.writerow([key, value, value])

I also want the dictionaries to be listed in the same corresponding order in the CSV file. As shown in the table, I want row1: 2248433.0 to correspond to 27.2.

This was the code used to generate dictionaries:

yin = {}
BL = {}
  for asdf in glob.glob(ay):
    poregn = numpy.genfromtxt(asdf)
    btwnROIs = poregn[2:size+2, 0:size] 
    BLu = poregn[(size*5)+2:(size*5)+size+2, 0:size]
    for upmatSC in (list(combinations(range(size_FC),2))):
      yin[FC_path1 + '_' + FC_path2 + '_' + str(upmatSC)] = btwnROIs[tuple(upmatSC)]
      BL[FC_path1 + '_' + FC_path2 + '_' + str(upmatSC)] = BLu[tuple(upmatSC)]

To explain the code: basically I'm taking two separate matrices and extracting the upper half of each of the matrix and storing these values in two separate dictionaries.

Upvotes: 0

Views: 782

Answers (1)

J. Taylor
J. Taylor

Reputation: 4865

If you have two dictionaries yin and bl, this would be how you would combine the dictionaries in the manner you described and write them to a CSV file:

import csv 

yin = {'a': 2248433.0, 'b': 280955.0, 'c': 0.0}
bl = {'a': 27.2, 'b': 57.6, 'c': 0.0}

with open('output.csv', 'w') as output:
    cw = csv.writer(output)

    for k in yin.keys():
      cw.writerow([k, yin[k], bl[k]])

Upvotes: 1

Related Questions