【问题标题】:python save dictionary to csv in same orderpython以相同的顺序将字典保存到csv
【发布时间】:2018-07-29 14:15:56
【问题描述】:

这是我的实际代码:

import csv

fb_catalog_dict = {
    "id":"",
    "title":"",
    "description":"",
    "availability":"",
    "condition":"",
    "price":"",
    "link":"",
    "image_link":"",
    "brand":"",
    "additional_image_link":"",
    "age_group":"",
    "color":"",
    "gender":"",
    "item_group_id":"",
    "google_product_category":"",
    "material":"",
    "pattern":"",
    "product_type":"",
    "sale_price":"",
    "sale_price_effective_date":"",
    "shipping":"",
    "shipping_weight":"",
    "size":"",
    "custom_label_0":"",
    "custom_label_1":"",
    "custom_label_2":"",
    "custom_label_3":"",
    "custom_label_4":"",
}



with open('mycsvfile.csv', 'wb') as f:  # Just use 'w' mode in 3.x
    w = csv.DictWriter(f, fb_catalog_dict.keys())
    w.writeheader()
    w.writerow(fb_catalog_dict)

我想在 csv 中以相同的顺序在 fb_catalog_dict 中创建相同的字典,问题是 python 为我创建具有不同顺序字段的 csv 文件,我该如何解决这个问题?

【问题讨论】:

    标签: python csv dictionary export-to-csv


    【解决方案1】:

    在 CPython >= 3.6 中,这将按照编写的方式工作,因为 dicts are ordered now

    在任何早期的 Python 版本(或不同的实现)上,您都可以使用 collections.OrderedDict。它的功能正如其名称所暗示的那样。

    您必须稍微更改您的实例化,因为将dict 传递给OrderedDict 只会保留dict 的顺序,而不是您编写它的顺序。因此,只需将其设为元组列表,as recommended here


    示例代码:

    import csv
    from collections import OrderedDict
    
    fb_catalog_dict = OrderedDict([
        ("id", ""),
        ("title", ""),
        ("description", ""),
        ("availability", ""),
        ...
        ])
    
    with open('mycsvfile.csv', 'wb') as f:  # Just use 'w' mode in 3.x
        w = csv.DictWriter(f, fb_catalog_dict.keys())
        w.writerow(fb_catalog_dict)
    

    (不确定你的 header 是什么,所以我把它省略了。)

    【讨论】:

    • @JulianMedic 见编辑。但我会在几秒钟内添加一些示例代码。
    • 我使用 python 2.7
    【解决方案2】:

    字典是无序的。并且鉴于您无论如何只使用密钥,您正在做的事情可以通过列表来实现。即:

    fb_catalog = [
        "id",
        "title",
        "description",
    ]
    

    等等。

    【讨论】:

      【解决方案3】:

      在 Python 中,dict 是无序结构。字典中没有特定的顺序。所以我看到的唯一方法是使用字段列表来确保您始终以相同的顺序获取它们:

      import csv
      
      d = {'1':1,'2':2,'z':'z'} 
      
      def fb_catalog_dict(fields_list,dict_object):
          return [dict_object[f] if f in dict_object else None for f in fields_list]
      
      f = open('mycsvfile.csv', 'w',newline='')
      writer = csv.writer(f)
      
      for i in range(10):
          writer.writerow(get_values_from_dict(['z','1','2'],d))
      f.close()
      

      P.S> 示例适用于 Python 3.x

      【讨论】:

        猜你喜欢
        • 2020-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多