使用标题索引和cs格式化值

2024-03-28 20:44:33 发布

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

我有一个.csv文件,我需要使它看起来像一个特定格式的字典,我不能把我的头围绕着循环必须这样做我需要的方式。例如,这三行(行[0]是带有我的标签的标题)当前看起来像:

0 outlook,temperature,humidity,windy,result
1 overcast,hot,high,FALSE,yes
2 overcast,cool,normal,TRUE,yes
...

应该是这样的:

 {"outlook":"overcast", "temperature":"hot", "humidity":"high","windy":"FALSE","result":"yes"},
 {"outlook":"overcast", "temperature":"cool", "humidity":"normal","windy":"TRUE","result":"yes"},
 ...

一旦他们被处理和清理。我已经很接近了,但不太适合用字典。我一直在捣乱熊猫和进口csv,我开始失去什么最好的方式在Py3是这样做的轨道。你知道吗

谢谢你的帮助。非常感谢。你知道吗


Tags: csvfalse字典方式resultyesnormaltemperature
1条回答
网友
1楼 · 发布于 2024-03-28 20:44:33

您可以使用^{}

Create an object which operates like a regular reader but maps the information read into a dict whose keys are given by the optional fieldnames parameter. The fieldnames parameter is a sequence whose elements are associated with the fields of the input data in order. These elements become the keys of the resulting dictionary. If the fieldnames parameter is omitted, the values in the first row of the csvfile will be used as the fieldnames.

所以示例代码是:

import csv
with open('temperature.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(row)
        ...

会打印出来的

{"outlook":"overcast", "temperature":"hot", "humidity":"high","windy":"FALSE","result":"yes"},
...

相关问题 更多 >