📜  将列表的字典转换为 CSV 的Python程序

📅  最后修改于: 2022-05-13 01:55:26.979000             🧑  作者: Mango

将列表的字典转换为 CSV 的Python程序

给定列表 d 的字典,任务是编写Python程序将字典写入 CSV 文件。

解决这个问题的想法是将字典压缩,然后将其写入 CSV 文件。 Python提供了一个名为“csv”的内置模块,用于处理 CSV 文件。 csv.writer 类用于写入 CSV 文件。 csv.writer 类提供了两种写入 csv 文件的方法。

  • writerow(): writerow() 方法用于写入单行。
  • writerows(): writerows() 方法用于写入多行。
Python3
# Program to write a dictionary of list to csv
import csv
  
# dictionary of list
d = {"key1": ['a', 'b', 'c'], 
     "key2": ['d', 'e', 'f'], 
     "key3": ['g', 'h', 'i']}
  
# writing to csv file
with open("test.csv", "w") as outfile:
    
    # creating a csv writer object
    writerfile = csv.writer(outfile)
      
    # writing dictionary keys as headings of csv
    writerfile.writerow(d.keys())
      
    # writing list of dictionary
    writerfile.writerows(zip(*d.values()))


Python3
# Program to write a dictionary of list to csv
import csv
  
# dictionary of list
d = {"key1": ['a', 'b', 'c'], 
     "key2": ['d', 'e', 'f'], 
     "key3": ['g', 'h', 'i']}
  
# writing to csv file
with open("test.csv", "w") as outfile:
    
    # creating a csv writer object
    writerfile = csv.writer(outfile)
      
    # writing dictionary keys as headings of csv
    writerfile.writerow(d.keys())
      
    # writing list of dictionary
    writerfile.writerows(zip(*d.values()))


输出:

Python 的 zip()函数将 iterable 作为输入并返回一个迭代器对象。该迭代器生成一系列元组,每个元组具有来自每个可迭代对象的元素。

这里字典中的列表作为 zip() 的输入提供,它将返回一系列元组,每个元组都包含来自所有列表的元素,这些元组将被视为 CSV 文件的行。

例子:

Python3

# Program to write a dictionary of list to csv
import csv
  
# dictionary of list
d = {"key1": ['a', 'b', 'c'], 
     "key2": ['d', 'e', 'f'], 
     "key3": ['g', 'h', 'i']}
  
# writing to csv file
with open("test.csv", "w") as outfile:
    
    # creating a csv writer object
    writerfile = csv.writer(outfile)
      
    # writing dictionary keys as headings of csv
    writerfile.writerow(d.keys())
      
    # writing list of dictionary
    writerfile.writerows(zip(*d.values()))

输出: