当某些值为空时,如何从python字典中写入CSV文件

2024-06-26 14:55:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Python字典字典,并且存储了需要写入CSV文件的日期。在

我遇到的问题是,我读过的文件中的一些字典不包含该特定ID的任何信息,因此我的CSV文件列没有正确排列。在

示例

 d["first1"]["title"] = founder
  d["first1"]["started"] = 2005
  d["second1"]["title"] = CEO
  d["second1"]["favcolour"] = blue

所以当我使用以下代码时:

^{pr2}$

我的CSV文件将包含所有的信息,但是“started”和“favcolour”在同一列中,我希望它在列中只包含一个。在

提前谢谢大家


Tags: 文件csv代码信息id示例字典title
3条回答

您可以使用csv中的DictWriter类轻松地将稀疏字典附加到CSV中。唯一需要注意的是,您需要在开始时知道所有可能的字段。在

import csv

data = { "first": {}, "second": {} }
data["first"]["title"] = "founder"
data["first"]["started"] = 2005
data["second"]["title"] = "CEO"
data["second"]["favcolour"] = "blue"


fieldNames = set()

for d in data:
  for key in data[d].keys():
    # Add all possible keys to fieldNames, beacuse fieldNames is
    # a set, you can't have duplicate values
    fieldNames.add(key)


with open('csvFile.csv', 'w') as csvfile:
  # Initialize DictWriter with the list of fieldNames
  # You can sort fieldNames to whatever order you wish the CSV
  # headers to be in.
  writer = csv.DictWriter(csvfile, fieldnames=list(fieldNames))

  # Add Header to the CSV file
  writer.writeheader()

  # Iterate through all sub-dictionaries
  for d in data:
    # Add the sub-dictionary to the csv file
    writer.writerow(data[d])

建议如下:

d = {"first1": {"title": 'founder', "started": 2005}, "second1": {"title": 'CEO', "favcolour": 'blue'}}

columns = []
output = []
for key, value in d.iteritems():
    for ikey, ivalue in value.iteritems():
        if ikey not in columns:
            columns.append(ikey)
    ln = []
    for col in columns:
        if col not in value:
            ln.append('')
        else:
            ln.append(value[col])

    output.append(ln)

with open('file', 'w') as fl:
    csv_writer = csv.writer(fl)
    csv_writer.writerow(columns)
    for ln in output:
        print ln
        csv_writer.writerow(ln)

文件:

^{pr2}$

如果不需要让人阅读,您可以使用pickle

import pickle

# Write:
with open('filename.pickle', 'wb') as handle:
  pickle.dump(d, handle)

# Read:
with open('filename.pickle', 'rb') as handle:
  d = pickle.load(handle)

相关问题 更多 >