简体   繁体   中英

Creating a csv file from a dictionary

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

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.

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.

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