【问题标题】:Writing list of dictionaries in python to csv with specific field order将python中的字典列表写入具有特定字段顺序的csv
【发布时间】:2016-10-23 09:13:43
【问题描述】:

我有一个字典列表,其中包含随机键:值对。我还有一个列表 - 我想将字段写入 csv 文件的顺序(字典的基本键)。我使用下面的代码来编写 csv 文件。

lst=[{"b":2,"d":3},{"a":1,"b":1,"c":5},{"d":7,"c":1}...]  
order = ["a","b","c","d"]

keys = lst[index].keys()
with open('file.csv', 'wb') as output_file:
    dict_writer = csv.DictWriter(output_file, keys)
    dict_writer.writeheader()
    dict_writer.writerows(lst)

最终的 CSV 文件按顺序包含键:

b,d,a,c  
2,3,,  

但我要按照订单清单。我该怎么做?

【问题讨论】:

  • 你为什么传递lst[index].keys()而不是order
  • @BrenBarn:你想把它写下来作为答案吗?

标签: python csv


【解决方案1】:

这个 sn-p 产生你想要的输出

lst=[{"b":2,"d":3},{"a":1,"b":1,"c":5},{"d":7,"c":1}]  
order = ["a","b","c","d"]
with open('file.csv', 'w') as output_file:
    dict_writer = csv.DictWriter(output_file, order)
    dict_writer.writeheader()
    dict_writer.writerows(lst)

【讨论】:

    【解决方案2】:

    首先从字典列表中获取所有键
    第二次根据您的订单列表对键列表进行排序
    最后根据排序的键写入标题

    lst = [{'b': 2, 'd': 3}, {'a': 1, 'c': 5, 'b': 1}, {'c': 1, 'd': 7}]
    flatLst = set([ k for ele in lst for k in ele.keys()])
    def sortKey(x):
        return order.index(x) if x in order else len(order)
    orderedHeader = sorted( flatLst, key = lambda x:sortKey(x))
    with open(filePath,'wb') as f:
         w = csv.DictWriter(f,orderedHeader)
        w.writeheader()
        w.writerows(lst)
    

    输出:

    a   b   c   d
        2       3
    1   1   5   
            1   7
    

    【讨论】:

      【解决方案3】:

      您从未使用过order。创建 DictWriter 时只需传递它而不是 keys

      【讨论】:

        猜你喜欢
        • 2015-10-02
        • 2016-03-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-15
        • 1970-01-01
        • 2014-06-17
        • 1970-01-01
        相关资源
        最近更新 更多