I am working on a web scraping project, I am trying to save the results into a CSV file,
data = { 'address_area': area, 'address_district': district, 'website': website, 'branch_rating': rating, 'facilities_delivery': delivery, 'facilities_banquet': banquet, 'facilites_shisha': shisha, 'faciliteis_minumum': minumium, 'facilites_reservation': reservation, 'facilities_free_wifi': wifi, 'facilities_smoking_permited': smoking, 'facilities_eat_out': eat_out, 'facilities_private_parking': parking, 'facilities_price_range': price_range, 'facilities_kids_ares': kids_ares, 'branch_no': branch_no} mainlist.append(data) with open('filetest.csv', 'w') as f: writer = csv.writer(f) for value in mainlist: writer.writerow([value])
I want to save the key in the dictionary as columns and the values as a row, (keep in mind that the value pair in the dictionary refers to a variable that extracts data from a web site)
Advertisement
Answer
Here is a solution that can work for you. I added a second data item to your code (data2) and renamed the initial data element to data1.
mainlist = [] #initial data item data1 = { 'address_area': 'area1', 'address_district': 'district1', 'website': 'website1', 'branch_rating': 'rating1', 'facilities_delivery': 'delivery1', 'facilities_banquet': 'banquet1', 'facilites_shisha': 'shisha1', 'faciliteis_minumum': 'minumium1', 'facilites_reservation': 'reservation1', 'facilities_free_wifi': 'wifi1', 'facilities_smoking_permited': 'smoking1', 'facilities_eat_out': 'eat_out1', 'facilities_private_parking': 'parking1', 'facilities_price_range': 'price_range1', 'facilities_kids_ares': 'kids_aresa1', 'branch_no': 'branch_no1'} mainlist.append(data1) #second data item data2 = { 'address_area': 'area2', 'address_district': 'district2', 'website': 'website2', 'branch_rating': 'rating2', 'facilities_delivery': 'delivery2', 'facilities_banquet': 'banquet2', 'facilites_shisha': 'shisha2', 'faciliteis_minumum': 'minumium2', 'facilites_reservation': 'reservation2', 'facilities_free_wifi': 'wifi2', 'facilities_smoking_permited': 'smoking2', 'facilities_eat_out': 'eat_out2', 'facilities_private_parking': 'parking2', 'facilities_price_range': 'price_range2', 'facilities_kids_ares': 'kids_aresa2', 'branch_no': 'branch_no2'} mainlist.append(data2) filename = 'filetest.csv' headers = ",".join(data1.keys()) with open(filename, 'w') as f: f.write(headers + 'n') for item in mainlist: f.write(','.join(str(item[key]) for key in item) + 'n') print("All done. Check this file for results:",filename)