简体   繁体   中英

How to convert a dictionary and write it into a CSV file?

#!/bin/python

import csv

my_dict = {'Age': ['22', '23', '34'], 'Name': ['Dinesh', 'Suresh', 'Mahesh']}


print(my_dict)

with open('Names.csv', 'w') as f:
    fieldnames = ['Age', 'Name']
    writer = csv.DictWriter(f, fieldnames=fieldnames)
    writer.writeheader()
    data = [dict(zip(fieldnames, [k, v])) for k, v in my_dict.items()]
    writer.writerows(data)

Using Python 2.7 ONLY

I want to write it to CSV file like:

Output: *输出*

If you'd rather have a solution that doesn't use Pandas, here's one:

import csv
with open('Names.csv', 'w') as f:
    fieldnames = ['Age', 'Name']
    writer = csv.DictWriter(f, fieldnames=fieldnames)
    writer.writeheader()
    data = [{"Name": k, "Age":v} for k, v in zip(my_dict["Sno"], my_dict["Name"])]
    writer.writerows(data)

Here's a simple pandas solution.

import pandas as pd

my_dict = {'Age': ['22', '23', '34'], 'Name': ['Dinesh', 'Suresh', 'Mahesh']}

df = pd.DataFrame(my_dict)

df.to_csv('Names.csv', index=False)

If you need to rename your Sno column, you can use:

df.rename(columns={'Sno':'Age'}, inplace=True)

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