我有一本字典,我想把它写进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)
您可以修改行:
write.writerows(val_list)
进入:
write.writerows(' '.join(map(str, val_list))
记住,这样做不会让的生活
res = pandas.read_csv('names.csv')
更容易。它可能不会像以前那样阅读东西。