将字典写入 csv 文件

希拉·纳贾姆

我有一本字典,我想将它写入 csv 文件。我将其转换为列表并尝试写入 csv 文件。我得到了答案,但与我要求的格式不同。这是我的代码

dic1 = {
    'Data': {
        'p_1': {
            'name': 'John', 
            'Interests': ['football', 'cricket']},
        'p_2': {
            'name': 'Smith', 
            'Interests': ['baseball', 'cricket']
                    }}}
import csv
import pandas
for k,v in dic1.items():
    val_list = []
    for k1, v1 in v.items():
        key = list(v1.keys())
        val = list(v1.values())
        val_list.append(val)

# wite the data into the csv file
with open('names.csv', 'w') as f:
    write = csv.writer(f)
    write.writerow(key)
    write.writerows(val_list)
    print('The file has been written')

# read the csv file with pandas
res = pandas.read_csv('names.csv')
print(res)

我以这种方式得到了输出:

    name                Interests
0   John  ['football', 'cricket']
1  Smith  ['baseball', 'cricket']

但要求的格式是:

    name                Interests
0   John        football, cricket
1  Smith        baseball, cricket

我怎样才能做到这一点?

阿努拉格·达巴斯

尝试:

df=pandas.DataFrame({y:z for k,v in dic1.items() for y,z in v.items()}.values())
#The above code doing the same thing via dict comprehension,here dic1 is your dictionary
df['Interests']=df['Interests'].str.join(',')
df.to_csv('names.csv',index=False)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章