使用 header 索引和 csv 格式化值

Formatting values using header indexing with csv

我有一个 .csv,我需要让它看起来像一个特定格式的字典,但我无法按照我需要的方式绕过必要的循环。例如,这三行(行 [0] 是带有我的标签的 header)当前看起来像:

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"},
 ...

一旦它们被处理和清理。我已经接近但不太正确使用字典。我一直在搞乱 pandas 和导入 csv,我开始忘记在 Py3 中执行此操作的最佳方法是什么。

感谢您的帮助。非常感谢。

您可以使用 DictReader:

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"},
...