【问题标题】:convert csv file to list of dictionaries将 csv 文件转换为字典列表
【发布时间】:2014-03-01 14:01:40
【问题描述】:

我有一个 csv 文件

col1, col2, col3
1, 2, 3
4, 5, 6

我想从这个 csv 创建一个字典列表。

输出为:

a= [{'col1':1, 'col2':2, 'col3':3}, {'col1':4, 'col2':5, 'col3':6}]

我该怎么做?

【问题讨论】:

    标签: python list csv dictionary


    【解决方案1】:

    使用csv.DictReader:

    import csv
    
    with open('test.csv') as f:
        a = [{k: int(v) for k, v in row.items()}
            for row in csv.DictReader(f, skipinitialspace=True)]
    

    将导致:

    [{'col2': 2, 'col3': 3, 'col1': 1}, {'col2': 5, 'col3': 6, 'col1': 4}]
    

    【讨论】:

    【解决方案2】:

    将 CSV 解析为字典列表的简单方法

    with open('/home/mitul/Desktop/OPENEBS/test.csv', 'rb') as infile:
      header = infile.readline().split(",")
      for line in infile:
        fields = line.split(",")
        entry = {}
        for i,value in enumerate(fields):
          entry[header[i].strip()] = value.strip()
          data.append(entry)
    

    【讨论】:

      【解决方案3】:

      另一个更简单的答案:

          import csv
          with open("configure_column_mapping_logic.csv", "r") as f:
              reader = csv.DictReader(f)
              a = list(reader)
              print a
      

      【讨论】:

      • 这会将它变成一个元组列表,而不是字典?
      • print(a) 应该在 with 块之外,因为那时不再需要该文件。另外:为什么不a = list(csv.DictReader(f))
      【解决方案4】:
      # similar solution via namedtuple:    
      
      import csv
      from collections import namedtuple
      
      with open('foo.csv') as f:
        fh = csv.reader(open(f, "rU"), delimiter=',', dialect=csv.excel_tab)
        headers = fh.next()
        Row = namedtuple('Row', headers)
        list_of_dicts = [Row._make(i)._asdict() for i in fh]
      

      【讨论】:

      • 只回答得到相同顺序的 CSV
      【解决方案5】:

      好吧,虽然其他人都在以聪明的方式做这件事,但我却天真地实现了它。我想我的方法的好处是不需要任何外部模块,尽管它可能会因值的奇怪配置而失败。这里仅供参考:

      a = []
      with open("csv.txt") as myfile:
          firstline = True
          for line in myfile:
              if firstline:
                  mykeys = "".join(line.split()).split(',')
                  firstline = False
              else:
                  values = "".join(line.split()).split(',')
                  a.append({mykeys[n]:values[n] for n in range(0,len(mykeys))})
      

      【讨论】:

        【解决方案6】:

        使用csv 模块和列表推导:

        import csv
        with open('foo.csv') as f:
            reader = csv.reader(f, skipinitialspace=True)
            header = next(reader)
            a = [dict(zip(header, map(int, row))) for row in reader]
        print a    
        

        输出:

        [{'col3': 3, 'col2': 2, 'col1': 1}, {'col3': 6, 'col2': 5, 'col1': 4}]
        

        【讨论】:

          猜你喜欢
          • 2019-02-01
          • 2014-04-24
          • 2011-03-06
          • 2018-01-14
          • 2017-03-27
          • 2020-01-03
          • 2018-06-23
          • 2016-01-28
          • 1970-01-01
          相关资源
          最近更新 更多