python以相同的顺序将字典保存到csv

Jul*_*dic 1 python csv dictionary export-to-csv

这是我的实际代码:

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)
Run Code Online (Sandbox Code Playgroud)

我希望在csv中以相同的顺序在fb_catalog_dict中使用相同的字典,问题是python使用不同的顺序fild创建我的csv文件,我该如何解决这个问题?

Gra*_*her 5

在CPython> = 3.6中,这将按书面形式工作,因为dicts现在是有序的.

在任何早期的Python版本(或不同的实现)上,您都可以使用collections.OrderedDict.它正是它的名字所暗示的.

你将不得不稍微改变您的实例,因为传递dictOrderedDict刚刚保存的顺序dict,而不是顺序你写的.因此,只需将其列为元组列表,如此处所建议的那样.


示例代码:

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)
Run Code Online (Sandbox Code Playgroud)

(不确定你的header定义是什么,所以我把它留了出来.)