I can not upload a dictionary to the csv file. Csv bay code

import csv parsing_data = [{'phrase': 'пс4', 'num': '88\xa0910', 'link': '/#!/?words=%D0%BF%D1%814'}, {'phrase': 'пс4 купить', 'num': '16\xa0207', 'link': '/#!/?words=%D0%BF%D1%814%20%D0%BA%D1%83%D0%BF%D0%B8%D1%82%D1%8C'}] output_file = open("pr1.csv", "w") wrtr = csv. DictWriter(output_file, fieldnames=["phrase", "num", "link"]) wrtr.writerow(["phrase", "num", "link"]) wrtr.writerow(parsing_data) 

in the phrase ps4 num should be equal to 88 910, in ps4 to buy 16 207. if after parsing output num (as a variable), then everything is displayed correctly, after writing to the dictionary, this conversion occurs How can I fix the situation?

Mistake

 Traceback (most recent call last): File "/home/ti/PycharmProjects/parserwordstat/parse.py", line 147, in <module> parse() File "/home/ti/PycharmProjects/parserwordstat/parse.py", line 106, in parse parse() File "/home/ti/PycharmProjects/parserwordstat/parse.py", line 111, in parse end_programm(parsing_data) File "/home/ti/PycharmProjects/parserwordstat/parse.py", line 19, in end_programm wrtr.writerow(["phrase", "num", "link"]) File "/usr/lib/python3.5/csv.py", line 153, in writerow return self.writer.writerow(self._dict_to_list(rowdict)) File "/usr/lib/python3.5/csv.py", line 150, in <genexpr> return (rowdict.get(key, self.restval) for key in self.fieldnames) AttributeError: 'list' object has no attribute 'get' 
  • one
    Arrange the code so that we can run it and get the same error, otherwise now there are syntax errors in general - andreymal
  • Corrected the code, made it compileable - Timur

1 answer 1

Since you are working with an object of type DictWriter , the writerow method writerow be passed not a list , but a dict object. That's why you get the AttributeError: 'list' object has no attribute 'get' error AttributeError: 'list' object has no attribute 'get'

Example:

 import csv data = [ {"name": "Tom", "age": 10, "city": "Moscow"}, {"name": "Mark", "age": 5, "city": "Khabarovsk"}, {"name": "Pam", "age": 7, "city": "Sahalin"} ] with open("file.csv", "w", newline="") as csv_file: csv_writer = csv.DictWriter(csv_file, fieldnames=data[0].keys()) csv_writer.writeheader() csv_writer.writerows(data) 
  • totally agree with you - Fedir Alifirenko