如何将两个字典写入CSV?

时间:2019-02-06 22:51:36

标签: python pandas csv dictionary file-writing

我想知道如何迭代两个字典:yinBL

到目前为止,我仅具有以下代码来遍历yin

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

yin在字典中具有值:

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

BL在字典中具有值:

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

我想将其保存到Excel文件中,使其看起来像:

a  2248433.0    27.2     
b  280955.0     57.6   
c  0.0           0.0

我应该执行以下操作吗?

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])

我还希望字典以相同的相应顺序在CSV文件中列出。如表所示,我希望row1: 2248433.0对应于27.2

这是用于生成字典的代码:

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)]

解释代码:基本上,我采用两个单独的矩阵,并提取每个矩阵的上半部分,并将这些值存储在两个单独的字典中。

1 个答案:

答案 0 :(得分:1)

如果您有两个字典yinbl,这将是您按照描述的方式组合字典并将它们写入CSV文件的方式:

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]])