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

发布于 2021-01-29 16:41:29

我有一本字典,其中的键是元组,值是列表,例如

{('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。没有有关按列编写的信息。

关注者
0
被浏览
48
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。
    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
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看