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

标签 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)

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

最佳答案

在 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 被定义为什么,所以我将其省略。)

关于python以相同的顺序将字典保存到csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48864578/

相关文章:

python - 按字母顺序从最高到最低和平均值对 csv 中的数据进行排序

linux - 仅从 CSV 文件的第 2 行和第 3 行中删除多余的逗号

python - 以良好可读的方式打印嵌套字典

python - 检查字典中是否存在特定的键和值

python - 使用Python,你如何纯粹在内存中解压?

python - 如何使用 Python 检查磁盘上还有多少可用空间?

python - 使用计数器 python 来自 2 个因式分解列表的 gcd

python - 当请求来自远程时, "nice"调试 django 的方法是什么?

python - 使用 Dask 加载多个 CSV 文件时混合列

python - 创建唯一列表 : comparing dict objects