Reputation: 19
#!/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:
Upvotes: 0
Views: 60
Reputation: 3086
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)
Upvotes: 0
Reputation: 12503
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)
Upvotes: 2