Reputation: 97
I have a dictionary like this:
culture= {13298341: [18.81,1155,'09-10-06',"['Africa', 'books', 'storytelling',
'writing']", 'The danger of a single story','Chimamanda Ngozi'],
14689301: [21.26,970,'06-09-25',"['TED Brain Trust', 'brain', 'evolution']",
'The surprising science of happiness','Dan Gilbert']}
Which each key has multiple values. How can I store this dictionary in a new csv file in a way that each key and each value be in one separated column?
The result should be a csv file like this:
views duration comments Published_date tags title speaker
13298341 18.81 1155 09-10-06 ['Africa', 'books', 'storytelling'] The danger of a single story Chimamanda Ngozi
14689301 21.26 970 06-09-25 ['TED Brain Trust', 'brain', 'evolution'] The surprising science of happiness Dan Gilbert
Upvotes: 0
Views: 107
Reputation: 2151
First, I removed the double-quotes around your list. I don't think they're needed, so hopefully that doesn't cause undue issues.
Second, hope you're okay with a pandas-centric solution.
import pandas as pd
culture= {13298341: [18.81, 1155, '09-10-06', ['Africa', 'books', 'storytelling', 'writing'],
'The danger of a single story','Chimamanda Ngozi'],
14689301: [21.26, 970, '06-09-25', ['TED Brain Trust', 'brain', 'evolution'],
'The surprising science of happiness','Dan Gilbert']}
df = pd.DataFrame(culture).transpose().reset_index()
df.columns = ['views', 'duration', 'comments', 'Published_date', 'tags', 'title', 'speaker']
df.set_index('views', inplace = True)
df.to_csv('df.csv')
Third, I'd recommend an index other than "views". You can get this by deleting the df.set_index(...)
line in the above.
ETA: Just checked and it works with the double quotes in there. I don't think it affects the CSV output. However, with the quotes, pandas stores the data as a string; without the quotes, it stores them as a list, which means you can access them via indexing. Cool.
Upvotes: 3