繁体   English   中英

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

[英]Python 3- Writing dictionaries with dictionary values to CSV files

我已经尝试过google-,但是找不到适合字典值的字典的解决方案。 让我解释一些简单。

我有一个票证代码字典,每个票证代码是另一个词典,包含“名称”和“兑现”-名称是票证所有者,而被兑现是票证是否已兑现。 数据是从名为TicketCodes的csv文件加载的,该文件包含1000行数据。 我有一个可以截断文件以准备写入的系统,但是我发现的写入CSV的解决方案不起作用。 如果这是重复的邮件,我深表歉意。 如果是,请您将我链接到解决方案吗? 非常感谢你!

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"}]'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM