【问题标题】:Save multiple dict values to a single csv row将多个 dict 值保存到单个 csv 行
【发布时间】:2015-11-03 17:58:06
【问题描述】:

我有以下文件,创建为defaultdict(lambda: defaultdict(dict))

{
 food_type1{
            brand1: a
            brand3: b
            }
 food_type2{
            brand1: c
            brand2: d
            brand3: e
            brand4: f
            }
 food_type3{
            brand2: g
            }
}

我还从列表中创建 CSV 标头,如下所示: "food_type", "brand1", "brand2", "brand3", "brand4"

字典无法更改,它需要具有那种结构,但如果需要,我可以将标题列表更改为更合适的内容(例如字典)。

我想创建一个包含列表中已定义标题的 CSV 文件,然后将字典中的值分配给每个 food_type 的相应键,如下所示:

"food_type",  "brand1", "brand2", "brand3", "brand4"
"food_type1", "a",       "",      "b",      ""
"food_type2", "c",       "d,",    "e",      "f"
"food_type3", "",        "g",     "",       ""

我尝试了for brand in food_type 循环,但这会为每个品牌创建一个新行,这不是我想要的。我需要在同一行中以所需的顺序将某个food_type 的所有相关信息都包含在内。

我怎样才能做到这一点?

【问题讨论】:

  • 发布您的一些代码,以便我们为您提供更多帮助。似乎您正在写入 for brand in food_type 循环内的 csv 文件,而您应该在 for food_type in dict 内写入
  • 你提前知道栏目吗?在开始查看数据之前,您知道总共只有 4 个品牌吗?
  • 是的,罗伯特,我确实提前知道了这些专栏。我可以查看它们的数量以及它们的名称。

标签: python csv python-3.x dictionary


【解决方案1】:

假设您知道字典中的每个键都属于 food_type 列,您可以使用 csv.DictWriter 和一些字典理解尝试以下脚本:

import csv

data = {
   "food_type1":{
              "brand1": "a",
              "brand3": "b"
              },
   "food_type2":{
              "brand1": "c",
              "brand2": "d",
              "brand3": "e",
              "brand4": "f"
              },
   "food_type3":{
              "brand2": "g"
              }
  }

headers = ["food_type",  "brand1", "brand2", "brand3", "brand4"]

with open("/tmp/test.csv", "w") as f:
    dict_writer = csv.DictWriter(f, headers, delimiter=',')
    dict_writer.writeheader()

    rows = []

    for key, row in data.iteritems():
        d = {header: row[header] if header in row else "" for header in headers}
        d["food_type"] = key
        rows.append(d)

    for row_dict in rows:
        dict_writer.writerow(row_dict)

【讨论】:

  • 这解决了它。唯一要评论的是,在 Python3 中,iteritems 应仅用作 items
猜你喜欢
  • 2020-11-18
  • 1970-01-01
  • 2020-08-10
  • 2022-01-02
  • 2018-03-08
  • 2018-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多