将多个dict值保存到单个cs

2024-10-16 22:34:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下文件,创建为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"

字典不能更改,它需要有这样的结构,但如果需要,我可以将标题列表更改为更合适的内容(例如dict)。在

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

^{pr2}$

我尝试过for brand in food_type循环,但这会为每个品牌创建一个新的行,这不是我想要的。我需要将某个food_type的所有相关信息放在同一行中,并按要求的顺序排列。在

我怎样才能做到这一点?在


Tags: 文件csvlambda标题列表字典foodtype
1条回答
网友
1楼 · 发布于 2024-10-16 22:34:00

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

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)

相关问题 更多 >