3

我有一个字典,其中键是元组,值是列表

{('c4:7d:4f:53:24:be', 'ac:81:12:62:91:df'): [5.998999999999998,0.0013169999,   
4.0000000000000972], ('a8:5b:4f:2e:fe:09', 'de:62:ef:4e:21:de'): [7.89899999,  
0.15647999999675390, 8.764380000972, 9.200000000]}  

我想将此字典以列格式写入 csv 文件,例如:

('c4:7d:4f:53:24:be', 'ac:81:12:62:91:df')    ('a8:5b:4f:2e:fe:09', 'de:62:ef:4e:21:de')  
             5.998999999999998                      7.89899999  
             0.0013169999                           0.15647999999675390
             4.0000000000000972                     8.764380000972   
                                                    9.200000000 

我知道使用代码以行格式编写同样的事情:

writer = csv.writer(open('dict.csv', 'wb'))
for key, value in mydict.items():
    writer.writerow([key, value])  

我如何在列中写相同的东西?甚至可能吗?提前感谢我在这里提到了 csv 的 python 文档:http: //docs.python.org/2/library/csv.html。没有关于按列写入的信息。

4

2 回答 2

2
import csv

mydict = {('c4:7d:4f:53:24:be', 'ac:81:12:62:91:df'):
          [5.998999999999998, 0.0013169999, 4.0000000000000972],
          ('a8:5b:4f:2e:fe:09', 'de:62:ef:4e:21:de'):
          [7.89899999, 0.15647999999675390, 8.764380000972, 9.200000000]}

with open('dict.csv', 'wb') as file:
    writer = csv.writer(file, delimiter='\t')
    writer.writerow(mydict.keys())
    for row in zip(*mydict.values()):
        writer.writerow(list(row))

输出文件 dict.csv:

('c4:7d:4f:53:24:be', 'ac:81:12:62:91:df')  ('a8:5b:4f:2e:fe:09', 'de:62:ef:4e:21:de')
5.998999999999998   7.89899999
0.0013169999    0.1564799999967539
4.000000000000097   8.764380000972
于 2013-07-19T01:37:24.960 回答
1

我相信你可以弄清楚格式:

>>> d.keys() #gives list of keys for first row
[('c4:7d:4f:53:24:be', 'ac:81:12:62:91:df'), ('a8:5b:4f:2e:fe:09', 'de:62:ef:4e:21:de')]
>>> for i in zip(*d.values()):  #gives rows with tuple structure for columns
        print i
(5.998999999999998, 7.89899999)
(0.0013169999, 0.1564799999967539)
(4.000000000000097, 8.764380000972)

对于您的代码,请执行以下操作:

writer = csv.writer(open('dict.csv', 'wb'))
writer.writerow(mydict.keys())  
for values in zip(*mydict.values()):
    writer.writerow(values)

() 等不会被添加到 csv 文件中。

于 2013-07-18T22:49:08.573 回答