In this post, we will see how we can convert a list of the dictionary to a CSV file using the Python CSV module.
In this sample python program, we will consider one list of a dictionary that we need to write in a CSV file and also will use dictionary keys as CSV file header.
So let's do it:
Convert Or Write Dictionary To A CSV File In Python
First, we will consider one list of dictionaries. Dictionary is nothing but a key-value pair enclosed within curly braces.
myDict=[{'id':'1','name':'ABC','address':'home','tell':123456
}, {'id':'2','name':'DEF', 'address':'home2','tell':12345678
}, {'id':'3','name':'GHI', 'address':'home3','tell':568445}]
Now we will create one function that will write a list Dictionaries into CSV and print the output. In this function, we used CSV module's DictReader and DictWriter classes.
#function to write Python Dictionary to CSV file
def dict_to_csv():
csv_column = ['id', 'name', 'address', 'tell']
myDict = [{'id': '1', 'name': 'ABC', 'address': 'home', 'tell': 123456
}, {'id': '2', 'name': 'DEF', 'address': 'home2','tell': 12345678
}, {'id': '3', 'name': 'GHI', 'address': 'home3','tell': 568445}]
csv_file = "temp.csv"
try:
with open(csv_file, 'w') as csvfile:
writer = csv.DictWriter(csvfile, myDict[0].keys())
writer.writeheader()
writer.writerows(myDict)
except IOError:
print("Something went wrong!!!")
Data = csv.DictReader(open(csv_file))
for row in Data:
print(row)
Full Programme Code:
import csv
#function to write Python Dictionary to CSV file
def dict_to_csv():
csv_column = ['id', 'name', 'address', 'tell']
myDict = [{'id': '1', 'name': 'ABC', 'address': 'home', 'tell': 123456
}, {'id': '2', 'name': 'DEF', 'address': 'home2', 'tell': 12345678
}, {'id': '3', 'name': 'GHI', 'address': 'home3', 'tell': 568445}]
csv_file = "temp.csv"
try:
with open(csv_file, 'w') as csvfile:
writer = csv.DictWriter(csvfile, myDict[0].keys())
writer.writeheader()
writer.writerows(myDict)
except IOError:
print("Something went wrong!!!")
Data = csv.DictReader(open(csv_file))
for row in Data:
print(row)
#main calling function
def main():
dict_to_csv()
if __name__ == '__main__':
main()
Output:
Below output will get print:
OrderedDict([('id', '1'), ('name', 'ABC'), ('address', 'home'), ('tell', '123456')])
OrderedDict([('id', '2'), ('name', 'DEF'), ('address', 'home2'), ('tell', '12345678')])
OrderedDict([('id', '3'), ('name', 'GHI'), ('address', 'home3'), ('tell', '568445')])
No comments:
Post a Comment