简体   繁体   English

如何将字典写入csv文件?

[英]How can I write a dictionary to a csv file?

The dictionary looks like the following. 该词典如下所示。

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

I want to get rid of ' [ ] in my csv file 我想在我的csv文件中删除'[]

I want to get the output csv as, 我想将输出csv作为

Qatar 68.61994212 59.03245947 55.10905996 卡塔尔68.61994212 59.03245947 55.10905996

Burundi 0.051012487 0.048311391 0.046681908 布隆迪0.051012487 0.048311391 0.046681908

Japan 9.605144835 9.247590692 9.542878595 日本9.605144835 9.247590692 9.542878595

Try the code below. 试试下面的代码。 The reason you are getting '[]' is because you might be trying to write the val of the dictionary as-is which is a list. 之所以得到'[]'是因为您可能试图按原样编写列表的字典的val。 Instead you need to retrieve the values in the list and then write it. 相反,您需要检索列表中的值,然后将其写入。

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)

OUTPUT : 输出

The contents of the file (result.csv) are as below: 文件(result.csv)的内容如下:

Burundi,0.051012487,0.048311391,0.046681908
Japan,9.605144835,9.247590692,9.542878595
Qatar,68.61994212,59.03245947,55.10905996

Aside from Jay-s answer if you are allowed to use Pandas then you can use panda-s to_csv function to just make the csv in one line. 除了Jay-s的答案之外,如果允许使用Pandas,则可以使用panda-s的to_csv函数将csv放在一行中。

import pandas as pd

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

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

You will get list of tuples likes this which you can write to a csv file: 您将获得像这样的元组列表,您可以将其写入csv文件:

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

Pandas will do it: 熊猫会做到这一点:

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)

Be sure to use "orient='index'" when creating the dataframe so that you get the correct row indexing in the csv 确保在创建数据框时使用“ orient ='index'”,以便在csv中获得正确的行索引

Qatar,68.61994212,59.03245947,55.10905996
Burundi,0.051012487,0.048311391,0.046681908
Japan,9.605144835,9.247590692,9.542878595

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

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