如何将两个字典写入CSV?

How to write two dictionaries to CSV?

我想知道如何迭代两个字典: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 文件中以相同的相应顺序列出。如table所示,我希望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)]

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

如果您有两个词典 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]])