我有以下文件,创建为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
的相应键,如下所示:
我尝试过for brand in food_type
循环,但这会为每个品牌创建一个新的行,这不是我想要的。我需要将某个food_type
的所有相关信息放在同一行中,并按要求的顺序排列。在
我怎样才能做到这一点?在
假设您知道字典中的每个键都属于
food_type
列,那么可以使用csv.DictWriter
和一些dict理解来尝试以下脚本:相关问题 更多 >
编程相关推荐