Python Forum
Appending a dictionary to csv file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Appending a dictionary to csv file
#1
Hi,

In a for loop I initially have the following dictionary:

dict1={'a':[[1,2],[3,4],[5,6]],'b':[[11,22],[33,44],[55,66]],'c':[[111,222],[333,444],[555,666]]}

I want to write it to a csv file as such:

Output:
[1,2],[3,4],[5,6] [11,22],[33,44],[55,66] [111,222],[333,444],[555,666]
In the next iteration of the loop dict1 becomes:

dict1={'a':[[7,8],[9,10]],'b':[[77,88],[99,100]],'c':[[777,888],[999,1000]]

and I want to append this to the previous csv file as such:

Output:
[1,2],[3,4],[5,6],[7,8],[9,10] [11,22],[33,44],[55,66],[77,88],[99,100] [111,222],[333,444],[555,666],[777,888],[999,1000]
I currently have this code:
if len(dict1)!=0:
    with open('dict1.csv', 'a+', encoding='utf8', newline='') as f:
         fc = csv.DictWriter(f, fieldnames=dict1.keys())
         fc.writerows(dict1)
This result in the following error:
Error:
Traceback (most recent call last): File "Gain_readDataT.py", line 279, in signalGain fc.writerows(dict1) File "/usr/lib/python3.6/csv.py", line 158, in writerows return self.writer.writerows(map(self._dict_to_list, rowdicts)) File "/usr/lib/python3.6/csv.py", line 148, in _dict_to_list wrong_fields = rowdict.keys() - self.fieldnames AttributeError: 'str' object has no attribute 'keys'
Any ideas how I might do this correctly?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Appending a row of data in an MS Excel file azizrasul 3 1,138 Nov-06-2022, 05:17 PM
Last Post: azizrasul
  Print to a New Line when Appending File DaveG 0 1,189 Mar-30-2022, 04:14 AM
Last Post: DaveG
Question How do I skipkeys on json file read to python dictionary? BrandonKastning 3 1,830 Mar-08-2022, 09:34 PM
Last Post: BrandonKastning
  trying to write a dictionary in a csv file CompleteNewb 13 6,381 Mar-04-2022, 04:43 AM
Last Post: deanhystad
  Appending Excel column value as CSV file name sh1704 0 1,267 Feb-06-2022, 10:32 PM
Last Post: sh1704
  File not appending Nu2Python 3 1,334 Jan-19-2022, 10:02 AM
Last Post: Larz60+
  Appending some rows in a .csv file from another .csv file tester_V 1 1,560 Aug-26-2020, 01:04 AM
Last Post: tester_V
  saving a dictionary as json file vinay_py 6 3,031 Jun-06-2020, 05:07 PM
Last Post: vinay_py
  problem coverting string data file to dictionary AKNL 22 6,265 Mar-10-2020, 01:27 PM
Last Post: AKNL
  Read csv file, parse data, and store in a dictionary markellefultz20 4 4,486 Nov-26-2019, 03:33 PM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020