The text below is selected, press Ctrl+C to copy to your clipboard. (⌘+C on Mac) No line numbers will be copied.
Guest
Python Help: Error: csv.DictWriter - AttributeError: list object has no attribute keys. Solution with working example: writer.writeheader()
By Guest on 8th November 2022 11:02:08 PM | Syntax: PYTHON | Views: 195



New Paste New paste | Download Paste Download | Toggle Line Numbers Show/Hide line no. | Copy Paste Copy text to clipboard
  1. Problem: trying to write header row in csv file.
  2.  
  3.  
  4. ###### read json file ######################
  5. with open('test.json', 'r') as j:
  6.     reader = json.load(j)
  7.     for row in reader:
  8.         print(row)
  9.  
  10. print(type(reader[0]))
  11. print(list(reader[0].keys()))
  12.  
  13. ######### write json back to csv file ###################
  14. with open('test2.csv', 'w', encoding='utf-8', newline='') as fcsv:
  15.     fnames = list(reader[0].keys())
  16.     writer = csv.DictWriter(fcsv, fieldnames=fnames, )
  17.     writer.writerow(fnames) #--- this is what caused the error
  18.     for row in reader:
  19.         print(type(row))
  20.         writer.writerow(row)
  21.  
  22. >>>
  23. ---------------------------------------------------------------------------
  24. AttributeError                            Traceback (most recent call last)
  25. c:\test\testjson.ipynb Cell 1 in <module>
  26.      29 fnames = list(reader[0].keys())
  27.      30 writer = csv.DictWriter(fcsv, fieldnames=fnames, )
  28. ---> 31 writer.writerow(fnames)
  29.      32 for row in reader:
  30.      33     print(type(row))
  31.  
  32. File c:\Python3\lib\csv.py:154, in DictWriter.writerow(self, rowdict)
  33.     153 def writerow(self, rowdict):
  34. --> 154     return self.writer.writerow(self._dict_to_list(rowdict))
  35.  
  36. File c:\Python3\lib\csv.py:147, in DictWriter._dict_to_list(self, rowdict)
  37.     145 def _dict_to_list(self, rowdict):
  38.     146     if self.extrasaction == "raise":
  39. --> 147         wrong_fields = rowdict.keys() - self.fieldnames
  40.     148         if wrong_fields:
  41.     149             raise ValueError("dict contains fields not in fieldnames: "
  42.     150                              + ", ".join([repr(x) for x in wrong_fields]))
  43.  
  44. AttributeError: 'list' object has no attribute 'keys'
  45.  
  46.  
  47. Test solution: use writer.writeheader() to add the header row - hard coded list of field names for testing
  48.  
  49. ######### write json back to csv file ###################
  50. with open('test2.csv', 'w', encoding='utf-8', newline='') as fcsv:
  51.     fnames = ['PassengerId', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp', 'Parch', 'Ticket', 'Fare', 'Cabin', 'Embarked']
  52.     writer = csv.DictWriter(fcsv, fieldnames=fnames, )
  53.     writer.writeheader()
  54.     for row in reader:
  55.         #print(type(row))
  56.         writer.writerow(row)
  57.  
  58.  
  59. Final solution: without hard-coding the field names. Get them directly from the Json reader list object.
  60.  
  61. ######### write json back to csv file ###################
  62. with open('test3.csv', 'w', encoding='utf-8', newline='') as fcsv:
  63.     fnames = list(reader[0].keys())
  64.     writer = csv.DictWriter(fcsv, fieldnames=fnames, )
  65.     writer.writeheader()
  66.     for row in reader:
  67.         #print(type(row))
  68.         writer.writerow(row)
  69.  
  70.  
  71. ------
  72. test.csv contents:
  73.  
  74. PassengerId,Pclass,Name,Sex,Age,SibSp,Parch,Ticket,Fare,Cabin,Embarked
  75. 892,3,"Kelly, Mr. James",male,34.5,0,0,330911,7.8292,,Q
  76. 893,3,"Wilkes, Mrs. James (Ellen Needs)",female,47,1,0,363272,7,,S
  77. 894,2,"Myles, Mr. Thomas Francis",male,62,0,0,240276,9.6875,,Q
  78. 895,3,"Wirz, Mr. Albert",male,27,0,0,315154,8.6625,,S
  79.  
  80.  
  81. Related video:
  82. Writing CSV Files with csv.writer and DictWriter
  83. https://www.youtube.com/watch?v=jnkPnNaLY3g
















Python software and documentation are licensed under the PSF License Agreement.
Starting with Python 3.8.6, examples, recipes, and other code in the documentation are dual licensed under the PSF License Agreement and the Zero-Clause BSD license.
Some software incorporated into Python is under different licenses. The licenses are listed with code falling under that license. See Licenses and Acknowledgements for Incorporated Software for an incomplete list of these licenses.

Python and it's documentation is:
Copyright © 2001-2022 Python Software Foundation. All rights reserved.
Copyright © 2000 BeOpen.com. All rights reserved.
Copyright © 1995-2000 Corporation for National Research Initiatives. All rights reserved.
Copyright © 1991-1995 Stichting Mathematisch Centrum. All rights reserved.

See History and License for complete license and permissions information:
https://docs.python.org/3/license.html#psf-license
  • Recent Pastes