【问题标题】:Using Python to convert CSV file into multiple dict使用 Python 将 CSV 文件转换为多个 dict
【发布时间】:2021-12-05 08:01:34
【问题描述】:

我想将 CSV 文件转换为字典列表。 例如,我有一个 CSV 文件,其中包含以下顺序的数据:

姓名、爱好、年龄

萨米,足球,6

安吉拉,国际象棋,12

输出应该是这样的:

[

  {"name": "Sammy", "hobby": "football", "age": "6"},

  {"name": "Angela", "hobby": "chess", "age": "12"}

]

你有什么建议吗?

【问题讨论】:

标签: python csv dictionary


【解决方案1】:

如果您可以使用Pandas,可以这样做 -

import pandas as pd

df = pd.read_csv('/path/to/csv/file')
records = df.to_dict(orient='records')

输出应该像 -

[
  {"name": "Sammy", "hobby": "football", "age": "6"},
  {"name": "Angela", "hobby": "chess", "age": "12"}
]

在这里,我们将 csv 文件作为 pandas DataFrame 读取,然后将 dataframe 转换为 dict。如果pandas 不可用,请使用安装

pip install pandas

【讨论】:

    【解决方案2】:

    您可以仅将此代码与 csv 模块一起使用:

    import csv
    
    with open(filename, mode='r') as infile:
        reader = csv.reader(infile, skipinitialspace=True)
        keys = next(reader)
        ret_list = []
        for row in reader:
            ret_list.append({})
            for key, value in zip(keys, row):
                ret_list[-1][key] = value
    

    更新: 这是更实用的解决方案:

    import csv
    
    with open(filename, mode='r') as infile:
        reader = csv.DictReader(infile, skipinitialspace=True)
        d = [r for r in reader]
    

    【讨论】:

      【解决方案3】:

      这是一种创建字典列表的方法;

      import pandas as pd
      # Replace './a.xlsx' with path to your file
      # In case file is in csv use pd.read_csv instead
      df = pd.read_excel('./a.xlsx')
      
      # Create an empty list to hold the list of dictionaries
      list_of_dicts = list()
      
      # Use iterrows to iterate over all rows
      for index, row in df.iterrows():
      
          # Empty dictionary to be used as tmp value for each dict in list
          dict_person = {}
          # Iterate over each column on the row, update the dictionary key and value
          for col in range(len(row.index)):
              dict_person.update({str(row.index[col]) : row[col]})
          # Add the temporary dict to the list
          list_of_dicts.append(dict_person)
      

      会产生结果;

      [{'name': 'Sammy', 'hobby': 'football', 'age': 6},
       {'name': 'Angela', 'hobby': 'chess', 'age': 12}]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-02-18
        • 2019-10-17
        • 2019-01-04
        • 2020-12-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多