Home > Back-end >  Append dictionary to a csv file and back to dictionary
Append dictionary to a csv file and back to dictionary

Time:02-04

I am trying to append dictionary to csv file and then back to dictionary. I don't want to write it just to append it.

from tkinter import *
import csv
dictionary = {"Alex" : 5, "Ben": 10}
with open("dict.csv", "a") as csv_file:
  writer = csv.writer(csv_file)
  for key, value in dictionary.items():
    writer.writerow([key, value])
with open("dict.csv") as csv_file:
  reader = csv.reader(csv_file)
  dictionary = dict(reader)

print(dictionary)

I want to have output {"Alex" : 5, "Ben": 10} and it will get me ValueError: dictionary update sequence element #1 has length 0; 2 is required. Can somebody please help?

CodePudding user response:

The problem you had is that when you are looping through the dictionary items you are adding them as a list while you are loading them you are trying to convert the list into a dict which a list can not do as they don't have key value pairs.

Here is one way to fix it:

import csv

data_dictonary = {"Alex" : 5, "Ben": 10}
# append to file
with open("dict.csv", "a") as csv_file:
  writer = csv.DictWriter(csv_file)
  writer.writerow(data_dictonary) # you can write the whole dictionary to a file  
# read file and check contents
with open("dict.csv") as csv_file:
  reader = csv.reader(csv_file)
  dictionary = dict(reader)

print(dictionary)

source

CodePudding user response:

Why ValueError?

because when you trying to turn the reader to a dict using dict(reader) dict actually needs a sequence of tuples (actually any kind of iterator with length two) but the reader is a sequence of sequence, so dict Complains that the first element of reader sequence is a sequence with zero elements on it ...

What can I do

writing part of your solution is ok (but it can improve with csv.DictWriter) the real problem is when you want to read it... use csv.DictReader like this

import csv

data_dictonary = {"Alex" : 5, "Ben": 10}
# append to file
with open("dict.csv", "a") as csv_file:
  writer = csv.DictWriter(csv_file)
  writer.writerow(data_dictonary) # you can write the whole dictionary to a file  
# read file and check contents
with open("dict.csv", newline='') as csv_file:
  dictionary = csv.DictReader(csv_file)

print(dictionary)
  •  Tags:  
  • Related