Python 3-将字典值的字典写入CSV文件

时间:2015-07-11 10:59:28

标签: python csv dictionary

我已经尝试了谷歌 - 但我找不到适用于字典值字典的解决方案。让我解释一下。

我有一个票务代码字典,每个票证代码是另一个字典,包含' name'并且'兑换' - 作为机票所有者的名字并兑换票证是否已被兑换。数据从名为TicketCodes的csv文件加载,该文件包含1000行此数据。我有一个系统会截断文件准备写,但我找到的写入CSV的解决方案不起作用。如果这是重复,我道歉 - 我可能没有足够的搜索。如果是,请您将我链接到解决方案吗?非常感谢你!

1 个答案:

答案 0 :(得分:0)

JSON是一种更好的格式,用于写出Python dict数据。但是,如果您的所有dict都具有相同的密钥,那么您可以使用dict密钥作为列名来格式化CSV文档。

例如:

# Assuming the data is a list of dictionaries
the_data = [{'col1': 'data1', 'col2': 'data2'},
            {'col1': 'data3', 'col2': 'data4'},
            {'col1': 'data5', 'col2': 'data6'},
            {'col1': 'data7', 'col2': 'data8'}]

# Build a list of the column names.
# This could be done with list(the_data[0].keys())
# But then you have no control over the column ordering
column_names = ['col1', 'col2']

# Print out column names
print(",".join(column_names))

# Print out data
for row in the_data:
    print(",".join([row[field] for field in column_names]))

<强>输出:

col1,col2
data1,data2
data3,data4
data5,data6
data7,data8

注意:在我的示例中,我刚刚打印出CSV数据,但将此数据写入文件会很简单。

此外,要将the_data写入JSON格式,只需执行以下操作即可:

>>> import json
>>> json.dumps(the_data)

'[{"col2": "data2", "col1": "data1"}, {"col2": "data4", "col1": "data3"}, {"col2": "data6", "col1": "data5"}, {"col2": "data8", "col1": "data7"}]'