Saving dictionaries in csv file with Python (2023-09-23 00:24:48)
Dictionaries are one of the most important types of data in the Python programming language, which can store data in the form of keys and values. The dictionary data type is mutable and does not allow duplicate data to be recorded.
In the following script, using the csv library, we store the information stored in the data set in the csv file.
import csv field_names= ['No', 'Country', 'Capital'] Cities=[ {'No':1, 'Country':'Iran', 'Capital':'Tehran'}, {'No':1, 'Country':'Turkey', 'Capital':'Istanbul'}, {'No':1, 'Country':'Azerbaijan', 'Capital':'Baku'}, ] with open('Cities.csv', 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=field_names) writer.writeheader() writer.writerows(Cities)
Comments