i have a dictionary and i want to write it into the csv file. I converted it into the list and tried to write into the csv file. I am getting the answer but not in the same format as i required. This is my code
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)
I got the output in this way:
name Interests
0 John ['football', 'cricket']
1 Smith ['baseball', 'cricket']
But required format is:
name Interests
0 John football, cricket
1 Smith baseball, cricket
How can I do this?
Try:
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)
You can modify the line:
write.writerows(val_list)
into:
write.writerows(' '.join(map(str, val_list))
Remember, doing so will not make the life of:
res = pandas.read_csv('names.csv')
any easier. it might not read the things as it used to be.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.