在列中编写字典项的可能性

时间:2013-07-18 22:06:14

标签: python

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

{('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。没有列明智的写作信息。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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文件中。