[英]Python 3- Writing dictionaries with dictionary values to CSV files
I've tried google- but I've not been able to find a solution that works with dictionaries with dictionary values. 我已经尝试过google-,但是找不到适合字典值的字典的解决方案。 Let me explain a little simpler.
让我解释一些简单。
I have a dictionary of Ticket Codes, and with each ticket code is another dictionary, containing 'name' and 'redeemed'- name being the ticket owner and redeemed being whether the ticket has been redeemed. 我有一个票证代码字典,每个票证代码是另一个词典,包含“名称”和“兑现”-名称是票证所有者,而被兑现是票证是否已兑现。 The data is loaded from a csv file named TicketCodes, which contains 1000 lines of this data.
数据是从名为TicketCodes的csv文件加载的,该文件包含1000行数据。 I have a system that will truncate the file ready for writing, but the solutions I have found for writing to a CSV don't work.
我有一个可以截断文件以准备写入的系统,但是我发现的写入CSV的解决方案不起作用。 I apologize if this is a duplicate- I may not have searched hard enough.
如果这是重复的邮件,我深表歉意。 If it is, please can you link me to a solution?
如果是,请您将我链接到解决方案吗? Thank you very much!
非常感谢你!
JSON would be a much better format for writing out Python dict data. JSON是写出python dict数据的更好的格式。 However, if all of your dict's have the same keys then you could potentially format a CSV document with the dict key's as the column names.
但是,如果所有dict的键都相同,则可能会以dict的键作为列名来格式化CSV文档。
For example: 例如:
# 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]))
Output: 输出:
col1,col2
data1,data2
data3,data4
data5,data6
data7,data8
Note: In my example I have just printed out the CSV data but it would be trivial to write this data to a file. 注意:在我的示例中,我刚刚打印了CSV数据,但是将这些数据写入文件将是微不足道的。
Also, to write the_data
to JSON format it is as simple as doing the following: 另外,要将
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"}]'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.