将多个dict值保存到单个csv行

时间:2015-11-03 17:58:06

标签: python csv python-3.x dictionary

我有以下文件,创建为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的相应键,如下所示:

"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并且具有所需的顺序。

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

假设您知道字典中的每个键都属于WHERE CAST(CASE WHEN a.variable = 'X' THEN '10' ELSE a.variable END AS int) >= 2 列,您可以使用SELECT MEMBERS.scancode, MEMBERS.fname, MEMBERS.lname, MEMBERS.mtypeid, MEMBERS.status, MEMBERS.datejoin, MEMBERS.dateexpire, MEMBERS.daterenewal, ARTRANS.datetrans, ARTRANS.transdescription, ARTRANS.invoice, ARTRANSITEMS.itemdescription, ARTRANSITEMS.price, ARTRANSITEMS.quantity, PRODUCTS.description, PRODUCTS.scancode AS ProductCode, MEMBERTYPES.description AS MembershipType, SITES.sitename FROM ARTRANS INNER JOIN ARTRANSITEMS ON ARTRANS.transid = ARTRANSITEMS.transid INNER JOIN MEMBERS ON ARTRANS.memid = MEMBERS.memid INNER JOIN PRODUCTS ON ARTRANSITEMS.productid = PRODUCTS.productid INNER JOIN PRODUCTCATS ON PRODUCTS.productcatid = PRODUCTCATS.productcatid INNER JOIN SITES ON ARTRANS.siteid = SITES.siteid INNER JOIN MEMBERTYPES ON MEMBERS.mtypeid = MEMBERTYPES.mtypeid AND PRODUCTCATS.productcatgroupid = 2 AND NOT EXISTS (SELECT MEMBERS.memid FROM ARTRANS AS ART2 INNER JOIN ARTRANSITEMS ON ART2.transid = ARTRANSITEMS.transid INNER JOIN MEMBERS ON ART2.memid = MEMBERS.memid INNER JOIN PRODUCTS ON ARTRANSITEMS.productid = PRODUCTS.productid INNER JOIN PRODUCTCATS ON PRODUCTS.productcatid = PRODUCTCATS.productcatid INNER JOIN MEMBERTYPES ON MEMBERS.mtypeid = MEMBERTYPES.mtypeid AND PRODUCTCATS.productcatgroupid = 2 WHERE (ART2.memid = ARTRANS.memid) AND (ART2.datetrans BETWEEN @rvMonthTwoStart AND @rvMonthTwoEnd)) WHERE (ARTRANS.datetrans BETWEEN @rvMonthOneStart AND @rvMonthOneEnd) 和一些字典理解来尝试以下脚本:

food_type