others - python - 如何将字典写到csv文件中?

字典看起来像下面这样。


res = {'Qatar': ['68.61994212', '59.03245947', '55.10905996'],


'Burundi': ['0.051012487', '0.048311391', '0.046681908'],


'Japan': ['9.605144835', '9.247590692', '9.542878595', ]}



我想去掉csv文件中的[]"

我想得到类似这样输出的csv格式,

Qatar 68.619 94212 59.032 45947 55.109 05996

Burundi 0.051 012487 0.048 311391 0.046 681908

Japan 9.605 144835 9.247 590692 9.542 878595

时间:

尝试这个: [(k,) + tuple(res[k]) for k in res]

你将获得这样的元组列表,你可以将它写入csv文件:

[('Burundi', '0.051012487', '0.048311391', '0.046681908'), ('Japan', '9.605144835', '9.247590692', '9.542878595'), ('Qatar', '68.61994212', '59.03245947', '55.10905996')]


import csv



res = {'Qatar': ['68.61994212', '59.03245947', '55.10905996'],


'Burundi': ['0.051012487', '0.048311391', '0.046681908'],


'Japan': ['9.605144835', '9.247590692', '9.542878595', ]}



with open('./result.csv', 'w') as res_file:


 csv_writer = csv.writer(res_file)


 for k, v in res.items():


 res_val = [x for x in v]


 res_val.insert(0, k)


 csv_writer.writerow(res_val)



输出:

文件(result.csv )的内容如下所示:


Burundi,0.051012487,0.048311391,0.046681908


Japan,9.605144835,9.247590692,9.542878595


Qatar,68.61994212,59.03245947,55.10905996



如果允许使用Pandas,则可以使用Pandas to_csv函数来使csv成为一行。


import pandas as pd



df = pd.DataFrame(res)


df.to_csv('my_result.csv', index=False)



Pandas将执行以下操作:


import pandas as pd



res = {'Qatar': ['68.61994212', '59.03245947', '55.10905996'],


 'Burundi': ['0.051012487', '0.048311391', '0.046681908'],


 'Japan': ['9.605144835', '9.247590692', '9.542878595', ]}



df = pd.DataFrame.from_dict(res, orient='index')


df.to_csv('res.csv', header=False)



在创建数据帧时请务必使用orient ='index'以便在csv中获得正确的行索引。


Qatar,68.61994212,59.03245947,55.10905996


Burundi,0.051012487,0.048311391,0.046681908


Japan,9.605144835,9.247590692,9.542878595



...