【问题标题】:Converting a dictionary of tuple arrays to a CSV将元组数组的字典转换为 CSV
【发布时间】:2023-03-08 19:10:01
【问题描述】:

我正在尝试转换结构如下的字典:

{
    'AAA': [ ('col1', 1), ('col2', 2), ('col3', 3) ],
    'BBB': [ ('col2', 1), ('col3', 4) ],
    'CCC': [ ('col4', 7) ]
}

...进入如下结构的 csv:

key  col1, col2, col3, col4
AAA  1     2     3
BBB        1     4
CCC                    7

具体来说,我不知道这些列将被命名,或者需要创建哪些列,直到运行时,除了直接对应于键的key 列。如果没有为给定列提供数据,则将其视为空。

有没有简单的方法在 Python 中做到这一点?我试图避免将数据过度重新洗牌到不同的结构中,我看到的所有关于 numpy 的示例都涉及并行列表。我愿意使用 numpy 和 pandas 等库。

【问题讨论】:

    标签: python csv dictionary


    【解决方案1】:

    在不先处理字典的情况下,没有一种简单的方法可以满足您的要求。

    Python 有一个 csv 库:https://docs.python.org/2/library/csv.html,但在使用它之前,您必须拥有正确格式的数据。你最好的选择是DictWriter 类,它可以将字典作为每一行。您的元组可以很容易地转换为 dicts,因此您需要能够使用此类只是获取字段名(列名)的列表。

    这是我将您的信息打印到 csv 中的方式:

    from csv import DictWriter
    
    d = { 'AAA': [ ('c1', 1), ('c2', 2), ('c3', 3)],
          'BBB': [ ('c2', 1), ('c3', 4)],
          'CCC': [ ('c4', 7)]
        }
    
    # convert dictionary of tuples into list of dictionaries
    # and gather fieldnames at the same time
    rows = []
    fieldnames = set()
    for k in d.keys():
        # a list of (k, v) tuples can be converted to a dict
        # but watch out for duplicate keys!
        tmp = dict(d[k])
        fieldnames.update(tmp.keys())
        tmp['key'] = k
        rows.append(tmp)
    
    # add key to the front of the list, since sets are unordered
    # you could sort the fieldnames however you want here
    fieldnames = ['key'] + list(fieldnames)                                                                 
    
    # open the file and write the csv
    with open('out.csv', 'w') as csvfile:
        writer = DictWriter(csvfile, fieldnames=fieldnames)
    
        writer.writeheader()
        for row in rows:
            writer.writerow(row)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-03
      • 2016-03-11
      • 1970-01-01
      • 2017-10-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多