如何用python编写词典列表的csv

如何用python编写词典列表的csv,python,csv,dictionary,data-analysis,Python,Csv,Dictionary,Data Analysis,def get_followers_和_class_max(用户): 多数=[] 用户关注者=设置(关注者关注者[followers\u csv[“followers”]==用户][“user”]) 用户\u followers\u class=set(关注者\u csv[followers\u csv[“followers”]==user][“labels”]) 对于用户关注者中的每个用户: 追加(为追随者(每个用户)获取最大类) 返回最大值(多数) 测试=[] 对于集合中的每个用户(用户cs

def get_followers_和_class_max(用户): 多数=[] 用户关注者=设置(关注者关注者[followers\u csv[“followers”]==用户][“user”]) 用户\u followers\u class=set(关注者\u csv[followers\u csv[“followers”]==user][“labels”]) 对于用户关注者中的每个用户: 追加(为追随者(每个用户)获取最大类) 返回最大值(多数)

测试=[] 对于集合中的每个用户(用户csv[“用户”]): 尝试: followers\u polarity=获取\u followers\u和\u class\u max(每个用户) 除了(值错误): 极性=0 尝试: 跟随极性=获取跟随最大值(每个用户) 除了(值错误): 以下极性=0

def get_follow_follow_max(user):
majority = []
users_followed = set(follow_csv[follow_csv["user"] == user]["follows"])
users_followed_class = set(follow_csv[follow_csv["user"] == user]["follows"])
for each_user in users_followed:
    majority.append(get_maximum_class_for_followed_users(each_user))
return max(majority)
打印(测试)
我想用新字段创建一个新的csv文件。分类显示在终端上,但不创建新的csv文件。

您可以使用
StringIO
class()写入内存(不创建任何文件),然后写入终端。此示例将CSV数据写入
StringIO
对象并打印:

new_file =StringIO(newline='')   

#print(test[0].keys())
keys = test[0].keys()
with open('work.csv', 'w') as output_file:
    dict_writer = csv.DictWriter(output_file, keys)
    dict_writer.writeheader()
    dict_writer.writerows(test)
with open('work3','w',newline='') as f_out:
    f_out.write(output_file.getvalue())
印刷品:

import csv
from io import StringIO   # from StringIO import StringIO in case of Python2

test = [{'col1':1, 'col2':2, 'col3':3},
        {'col1':4, 'col2':5, 'col3':6}]

output_file = StringIO(newline='')

dict_writer = csv.DictWriter(output_file, ['col1', 'col2', 'col3'])
dict_writer.writeheader()
dict_writer.writerows(test)

output_file.seek(0)
print(output_file.read())
编辑:

要写入多个CSV文件,可以使用以下代码段:

col1,col2,col3
1,2,3
4,5,6

这将创建两个文件
work1.csv
work2.csv

您希望在终端上显示什么?你的问题不清楚。我的意思是说将输出保存到新的csv文件中。谢谢你的解释
import csv
from io import StringIO   # from StringIO import StringIO in case of Python2

test = [{'col1':1, 'col2':2, 'col3':3},
        {'col1':4, 'col2':5, 'col3':6}]

output_file = StringIO(newline='')

dict_writer = csv.DictWriter(output_file, ['col1', 'col2', 'col3'])
dict_writer.writeheader()
dict_writer.writerows(test)

output_file.seek(0)
print(output_file.read())
col1,col2,col3
1,2,3
4,5,6
import csv
from io import StringIO

test = [{'col1':1, 'col2':2, 'col3':3},
        {'col1':4, 'col2':5, 'col3':6}]

output_file = StringIO(newline='')

dict_writer = csv.DictWriter(output_file, ['col1', 'col2', 'col3'])
dict_writer.writeheader()
dict_writer.writerows(test)

with open('work1.csv', 'w', newline='') as f1_out, \
    open('work2.csv', 'w', newline='') as f2_out:

    f1_out.write(output_file.getvalue())
    f2_out.write(output_file.getvalue())