简体   繁体   English

将字典导出到 csv 文件:d={key:value} 值是一个列表

[英]export a dictionary to csv file : d={key : value} value is a list

I'm trying to output my dictionary as a CSV file.我正在尝试将 output 我的字典作为 CSV 文件。 But I didn't manage to do it properly.但我没能正确地做到这一点。 my output file looks very bad.我的 output 文件看起来很糟糕。 Does anyone have an idea of how to put values coming from in the same key in the same column?有谁知道如何将来自同一键的值放在同一列中?

dico = {'names': ['Jimmy', 'Drew'], 'age':[25, 30]}
df = pd.DataFrame.from_dict([dico])
df.to_csv('file.csv', sep='\t',header=True, index=False, mode='w')


# output file looks like this:
age names
[25, 30]    ['Jimmy', 'Drew']

I also tried:我也试过:

with open('mycsvfile.csv','w' ) as f:
    w = csv.DictWriter(f, fieldnames=dico.keys())
    w.writeheader()
    w.writerow(dico)

But the problem is the same但问题是一样的

The problem is in dataframe creation.问题出在 dataframe 创建中。 If you take a look at df, each cell contains an array:如果你看一下 df,每个单元格都包含一个数组:

>>> df
        age          names
0  [25, 30]  [Jimmy, Drew]

Replace the creation line with:将创建行替换为:

df = pd.DataFrame.from_dict(dico)

And csv will be saved as needed. csv 将根据需要保存。

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

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