如何将 csv 文件转换为 Python 中的字典?

How to convert a csv file to a Dictionary in Python?

我有一个 csv 文件,其中包含创建 yaml 文件的配置信息(最终期望的结果)。首先,我试图将 csv 文件的每一行转换为字典,然后我可以使用 yaml.dump(Created_Dictionary)

轻松地将字典转换为 yaml 文件

样本输入文件(test.csv):

fieldname|type|allowed|coerce
field_A|String|10,20,30|to_str
field_B|Integer||to_int

我的源代码使用 pandas 库:

df = pd.read_csv("test.csv", "|")
df_to_dict = df.to_dict(orient='records')
print(df_to_dict) # print the dictionary

test_yaml = yaml.dump(df_to_dict)
print(test_yaml) # print the yaml file

我得到的字典输出(df_to_dict):

[{'fieldname': 'field_A', 'type': 'String', 'allowed': '10,20,30'}, {'fieldname': 'field_B', 'type': 'Integer', 'allowed': nan}]

我为 yaml (test_yaml) 获得的输出:

- allowed: 10,20,30
  fieldname: field_A
  type: String
- allowed: .nan
  fieldname: field_B
  type: Integer

所需的字典输出 (df_to_dict) 是:

[
  {'field_A':
          {'type': 'String', 'allowed': '10,20,30', 'coerce': to_str}
       },
  {'field_B':
          {'type': 'String',  'allowed': '', 'coerce': to_int}
       } 
]

所需的 yaml 输出 (test_yaml) 是:

field_A:
  type: String
  allowed: 
  - '10'
  - '20'
  - '30'
  coerce: to_str
field_B:
  type: Integer
  allowed:
  coerce: to_int

我看到变量 df_to_dict 是一个字典列表。我是否必须遍历每个列表项然后为每一行构建字典?我不明白正确的方法。感谢任何帮助。

尝试:

df = pd.read_csv("test.csv", "|")
my_dict = df.set_index("fieldname").to_dict("index")

#convert allowed items to list
df["allowed"] = df["allowed"].str.split(",")
test_yaml = yaml.dump(df.set_index("fieldname").to_dict("index"), sort_keys=False)
输出:
>>> my_dict
{'field_A': {'type': 'String', 'allowed': '10,20,30', 'coerce': 'to_str'},
 'field_B': {'type': 'Integer', 'allowed': nan, 'coerce': 'to_int'}}

>>> print(test_yaml)
field_A:
  type: String
  allowed:
  - '10'
  - '20'
  - '30'
  coerce: to_str
field_B:
  type: Integer
  allowed: .nan
  coerce: to_int

您想使用 pandas DataFrame 的索引。

>>> df = pd.read_csv("test.csv", sep="|", index_col=0)
>>> df
              type   allowed
fieldname                   
field_A     String  10,20,30
field_B    Integer       NaN
>>> df.to_dict(‘index’) # returns dict like {index -> {column -> value}}
{'field_A': {'type': 'String', 'allowed': '10,20,30'}, 'field_B': {'type': 'Integer', 'allowed': nan}}
>>> print(yaml.dump(df.to_dict(‘index’)))
field_A:
  allowed: 10,20,30
  type: String
field_B:
  allowed: .nan
  type: Integer

.nan 您必须处理自定义转储或过滤器。

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_dict.html?highlight=to_dict#pandas.DataFrame.to_dict

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html

如果您不需要 Pandas,并且我在您的描述或示例中没有看到任何需要,请使用 Python 的内置 csv 库,及其 DictReader class.

import csv
import pprint

yaml_d = {}
with open('sample.csv', newline='') as f:
    reader = csv.DictReader(f, delimiter='|')
    for row in reader:
        fname = row['fieldname']
        allowed = row['allowed'].split(',')

        yaml_d[fname] = row             # "index" row by fieldname
        yaml_d[fname]['allowed'] = allowed

        del yaml_d[fname]['fieldname']  # remove now-extraneous fieldname from row


pprint.pprint(yaml_d)

让我明白:

{'field_A': {'allowed': ['10', '20', '30'],
             'coerce': 'to_str',
             'type': 'String'},
 'field_B': {'allowed': [''], 'coerce': 'to_int', 'type': 'Integer'}}