简体   繁体   English

在字典列表中写入具有字典名称的 CSV 文件

[英]Writing CSV file having the names of dictionaries in a list of dictionaries

Maybe it is a simple question but I can't find a similar one elsewhere.也许这是一个简单的问题,但我在其他地方找不到类似的问题。

I have a list of dictionaries like我有一个字典列表,例如

all_dictionaries=[dictio1, dictio2, dictio3]

And I would like to save those dictionaries to different CSV files with each file having the name of the dictionaries like: dictio1.csv , dictio2.csv , dictio3.csv And I would like to save those dictionaries to different CSV files with each file having the name of the dictionaries like: dictio1.csv , dictio2.csv , dictio3.csv

So far I have written this code, but looping over a list of dictionaries meaning looping over the items of the general all_dictionaries .到目前为止,我已经编写了这段代码,但是循环遍历字典列表意味着循环遍历一般all_dictionaries的项目。 The problem is in the filename variable where it doesn't recognize the dictionary as a string but rather as a dictionary.问题出在文件名变量中,它不将字典识别为字符串,而是将其识别为字典。 Any idea how to get the name of the dictionary and place it as a file name?知道如何获取字典的名称并将其作为文件名放置吗?

for dictio in all_dictionaries:
    filename="%s.csv" %dictio
    with open(filename, 'wb') as csv_file:
        writer=csv.writer(csv_file)
        for key, value in dictio.items():
            writer.writerow([key, value])

You can't have the "variable name" as filename here.您不能在此处将“变量名”作为文件名。 Maybe you should have a name key that has a filename as value in all of your dictionaries and then you can do a loop like...也许你应该有一个名称键,在你的所有字典中都有一个文件名作为值,然后你可以做一个循环,比如......

for dictio in all_dictionnaries:
    filename="%s.csv" %dictio['name']
    with open(filename, 'wb') as csv_file:
        writer=csv.writer(csv_file)
        for key, value in dictio.items():
            writer.writerow([key, value])

This may get tedious when you have lots of dicts to handle.当您有很多 dicts 需要处理时,这可能会变得乏味。 But i think this should work if you have small number of dicts.但是我认为如果您的字典数量很少,这应该可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM