【问题标题】:Python: How to create a csv string (no file) from a list of dictionaries?Python:如何从字典列表中创建 csv 字符串(无文件)?
【发布时间】:2020-02-05 13:31:33
【问题描述】:

在 Python 中,我有一个这样的字典列表:

[
    {
        "col2": "2",
        "id": "1",
        "col3": "3",
        "col1": "1"
    },
    {
        "col2": "4",
        "id": "2",
        "col3": "6",
        "col1": "2"
    },
    {
        "col1": "1",
        "col2": "4",
        "id": "3",
        "col3": "7"
    }
]

我需要将其转换为 csv 格式的字符串,包括标题行。 (对于初学者来说,让我们不关心列和行分隔符......) 所以,理想的结果是:

id,col1,col2,col3
1,1,2,3
2,2,4,6
3,1,4,7

(“理想”,因为列顺序并不重要;不过,首先有“id”列会很好......)

我搜索过 SOF 并且有许多类似的问题,但答案总是涉及使用 csv.DictWriter 创建一个 csv 文件。我不想创建文件,我只想要那个字符串!

当然,我可以遍历列表并在此循环内循环遍历字典键,并以这种方式使用字符串操作创建 csv 字符串。但肯定有一些更优雅、更有效的方法来做到这一点吗?

另外,我知道 Pandas 库,但我试图在一个非常有限的环境中执行此操作,我宁愿只使用内置模块。

【问题讨论】:

    标签: python string list csv dictionary


    【解决方案1】:

    您可以使用io.StringIO 写入“字符串”而不是文件。以csv.DictWriter为例,我们得到如下代码:

    import csv
    import io
    
    data = [...]  # your list of dicts
    
    with io.StringIO() as csvfile:
        fieldnames = ['id', 'col1', 'col2', 'col3']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    
        writer.writeheader()
        for row in data:
            writer.writerow(row)
        print(csvfile.getvalue())
    

    【讨论】:

      【解决方案2】:

      最简单的方法是使用 pandas:

      import pandas as pd
      df = pd.DataFrame.from_dict(your_list_of_dicts)
      print(df.to_csv(index=False))
      

      结果:

      col1,col2,col3,id
      1,2,3,1
      2,4,6,2
      1,4,7,3
      

      如果你想重新排序列,没有比这更简单的了:

      col_order = ['id', 'col1', 'col2', 'col3']
      df[col_order].to_csv(index=False)
      

      或者,只是确保 id 列在前:

      df.set_index('id', inplace=True) # the index is always printed first
      df.to_csv() # leave the index to True this time
      

      【讨论】:

      • pandas 对于这样一个微不足道的任务来说是相当严重的依赖
      【解决方案3】:

      内置功能:

      from collections import OrderedDict
      
      ord_d = OrderedDict().fromkeys(('id', 'col1', 'col2', 'col3'))
      s = ','.join(ord_d.keys()) + '\n'
      for d in lst:
          ord_d.update(d)
          s += ','.join(ord_d.values()) + '\n'
      
      print(s)
      

      输出:

      id,col1,col2,col3
      1,1,2,3
      2,2,4,6
      3,1,4,7
      

      【讨论】:

        【解决方案4】:

        这个想法是获取所有可能的键并获取所有值。 假设数据是您拥有的字典列表。 这应该有效:

        output = ''
        all_keys = set().union(*(d.keys() for d in data))
        output += ",".split(all_keys) + '\n'
        for item in data:
            item_str = ",".split([data[key] for key in all_keys if key in data else ''])
            output += item_str + '\n'
        

        source

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-02-19
          • 2015-09-16
          • 1970-01-01
          • 2022-11-17
          • 2014-11-11
          • 2016-12-02
          • 1970-01-01
          • 2016-09-03
          相关资源
          最近更新 更多