这是我的实际代码:
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 文件,我该如何解决这个问题?
最佳答案
在 CPython >= 3.6 中,这会像写的那样工作,因为 dict
s 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
被定义为什么,所以我将其省略。)
关于python以相同的顺序将字典保存到csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48864578/