如何将字典写入csv文件?

时间:2019-05-19 07:51:19

标签: python dictionary

该词典如下所示。

res = {'Qatar': ['68.61994212', '59.03245947', '55.10905996'],
'Burundi': ['0.051012487', '0.048311391', '0.046681908'],
'Japan': ['9.605144835', '9.247590692', '9.542878595', ]}

我想摆脱csv文件中的'[]

我想将输出csv作为

卡塔尔68.61994212 59.03245947 55.10905996

布隆迪0.051012487 0.048311391 0.046681908

日本9.605144835 9.247590692 9.542878595

4 个答案:

答案 0 :(得分:3)

尝试下面的代码。之所以得到'[]'是因为您可能试图按原样编写列表的字典的val。相反,您需要检索列表中的值,然后将其写入。

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

答案 1 :(得分:2)

除了允许您使用Jay-sPandas答案之外,您还可以使用panda -s to_csv函数将csv放在一行中。

import pandas as pd

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

答案 2 :(得分:0)

尝试一下: [(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')]

答案 3 :(得分:0)

熊猫会这样做:

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