【问题标题】:Write dictionary of lists to a CSV file将列表字典写入 CSV 文件
【发布时间】:2014-06-30 01:48:00
【问题描述】:

我正在努力将列表字典写入 .csv 文件。

这就是我的字典的样子:

dict[key1]=[1,2,3]
dict[key2]=[4,5,6]
dict[key3]=[7,8,9]

我希望 .csv 文件看起来像:

key1  key2  key3
1     4     7  
2     5     8
3     6     9

一开始我写了标题:

outputfile = open (file.csv,'wb')
writefile = csv.writer (outputfile)
writefile.writerow(dict.keys())

到目前为止一切顺利...但是,我的问题是我不知道如何将一个列表分配给相应的列。例如:

for i in range(0,len(dict[key1])):
    writefile.writerow([dict[key1][i],dict[key2][i],dict[key3][i])

将随机填充列。另一个问题是,我必须手动填写键并且不能将它用于另一个具有 4 个键的字典。

【问题讨论】:

  • “随机填充列”是什么意思?
  • @RobWatts 我认为 OP 意味着由于 dicts 是无序的,函数 keys() 将“随机”打印出来,例如。键 3、键 1、键 2
  • 顺便说一下,你不应该使用dict作为变量名。
  • dict 不是我真正的变量名...只是一个坏例子

标签: python csv dictionary


【解决方案1】:

即使 key 中的列表长度不同,这也会起作用。

    with myFile:  
        writer = csv.DictWriter(myFile, fieldnames=list(clusterWordMap.keys()))   
        writer.writeheader()
        while True:
            data={}
            for key in clusterWordMap:
                try:
                    data[key] = clusterWordMap[key][ind]
                except:
                    pass
            if not data:
                break
            writer.writerow(data)

您可以使用 pandas 将其保存到 csv 中:

df = pd.DataFrame({key: pd.Series(value) for key, value in dictmap.items()})
df.to_csv(filename, encoding='utf-8', index=False)

【讨论】:

  • df = pd.DataFrame(dict) 是创建数据框所需的全部内容。
  • 如果存储在字典中的值长度不同,它将失败
  • 你能定义 myFile、clusterWordMap 和 ind 吗?谢谢。
【解决方案2】:

保存:

with open(path, 'a') as csv_file:
    writer = csv.writer(csv_file)
    for key, value in dict_.items():
        writer.writerow([key, ','.join(value)])
csv_file.close()        
print ('saving is complete') 

回读:

with open(csv_path, 'rb') as csv_file:
    reader = csv.reader(csv_file);
    temp_dict = dict(reader);
mydict={k:v.split(',') for k,v in temp_dict.items()}    
csv_file.close()
return mydict 

【讨论】:

    【解决方案3】:

    在没有 csv 模块的情况下自行滚动:

    d = {'key1' : [1,2,3],
         'key2' : [4,5,6],
         'key3' : [7,8,9]}
    
    column_sequence = sorted(d.keys())
    width = 6
    fmt = '{{:<{}}}'.format(width)
    fmt = fmt*len(column_sequence) + '\n'
    
    output_rows = zip(*[d[key] for key in column_sequence])
    
    with open('out.txt', 'wb') as f:
        f.write(fmt.format(*column_sequence))
        for row in output_rows:
            f.write(fmt.format(*row))
    

    【讨论】:

      【解决方案4】:

      如果您不关心列的顺序(因为字典是无序的),您可以简单地使用zip()

      d = {"key1": [1,2,3], "key2": [4,5,6], "key3": [7,8,9]}
      with open("test.csv", "wb") as outfile:
         writer = csv.writer(outfile)
         writer.writerow(d.keys())
         writer.writerows(zip(*d.values()))
      

      结果:

      key3    key2    key1
      7       4       1
      8       5       2
      9       6       3
      

      如果您确实关心顺序,则需要对键进行排序:

      keys = sorted(d.keys())
      with open("test.csv", "wb") as outfile:
         writer = csv.writer(outfile, delimiter = "\t")
         writer.writerow(keys)
         writer.writerows(zip(*[d[key] for key in keys]))
      

      结果:

      key1    key2    key3
      1       4       7
      2       5       8
      3       6       9
      

      【讨论】:

      • 如何在此处将行更改为列 key1 \tab 7 \tab 4 \tab 1
      • 如果你看问题,我用zip()转置原始数据。如果您再次执行该操作,您将再次将行更改为列。请注意,key1 - 7 - 4 - 1 可能不是您想要的...
      • 这为我运行,我得到了我想要的输出,但它仍然抛出一个 typeError “zip 参数 #1 必须支持迭代”。这有什么原因吗?
      • 对,在 Python 2 上,您需要使用 wb,而在 Python 3 上,您需要在打开 CSV 文件时使用 newline='' 选项。
      • @JasonGoal 可能很晚了,但如果你仍然想知道这里的答案是一个要点,这个人完美地解释了它gist.github.com/captmomo/7836eb53b7cee9fb7d38460f70942902
      【解决方案5】:

      给定

      dict = {}
      dict['key1']=[1,2,3]
      dict['key2']=[4,5,6]
      dict['key3']=[7,8,9]
      

      以下代码:

      COL_WIDTH = 6
      FMT = "%%-%ds" % COL_WIDTH
      
      keys = sorted(dict.keys())
      
      with open('out.csv', 'w') as csv:
          # Write keys    
          csv.write(''.join([FMT % k for k in keys]) + '\n')
      
          # Assume all values of dict are equal
          for i in range(len(dict[keys[0]])):
              csv.write(''.join([FMT % dict[k][i] for k in keys]) + '\n')
      

      生成如下所示的 csv:

      key1  key2  key3
      1     4     7
      2     5     8
      3     6     9
      

      【讨论】:

        【解决方案6】:
        key_list = my_dict.keys()    
        limit = len(my_dict[key_list[0]])    
        
        for index in range(limit):    
          writefile.writerow([my_dict[x][index] for x in key_list])
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-10-26
          • 2014-06-17
          • 2018-07-18
          • 2023-03-03
          • 2016-03-01
          • 1970-01-01
          相关资源
          最近更新 更多