JSON将是写出Python字典数据更好的格式。但是,如果您的所有字典都具有相同的密钥,那么您可以使用字典密钥作为列名格式化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"}]'
请出示您已经尝试的代码,你得到了错误。 –
首先关注我上面的评论。之后,查询我的水晶球,我认为数据结构的适当序列化格式可能是JSON(您的字典的值是字典)。 –
门票词典?所以它其实是一个集合?如果是这样,关键是什么,你需要存储它?最好给一个样本入口完成。 – tutuDajuju