-1

I have the code below to save a dictionary to csv in python. How can I load this back in?

There are a few answers on here, but none seem to be working

file='Location'
with open(file, 'w') as f:  # Just use 'w' mode in 3.x
    w = csv.DictWriter(f, mydic.keys())
    w.writeheader()
    w.writerow(mydic)
fred.schwartz
  • 2,023
  • 4
  • 26
  • 53

2 Answers2

1

I would suggest to save a dictionary as json file.

import json

with open('data.json', 'w') as fp:
    json.dump(mydic, fp)

To load the json file:

with open('data.json', 'r') as fp:
    mydic = json.load(fp)
Jeril
  • 7,858
  • 3
  • 52
  • 69
0

I believe a way to deal with saving and loading dictionary is to use pickle

Saving:

import pickle
some_file = open("file", "wb")
my_dictionary = {"aa":"aa"}
pickle.dump(my_dictionary, some_file)
some_file.close()

Reading back:

import pickle
some_file = open("file", "r")
my_dictionary = pickle.load(some_file)

Please remember that using pickle is not safe while dealing with data received from the untrusted source.

Laszlowaty
  • 1,295
  • 2
  • 11
  • 19
  • Define "correct". For flat dictionaries and simple values, a CSV will do fine as well. – deceze Apr 16 '19 at 11:56
  • It's simple, efficient and universal. It's marshalling by python. It doesn't require to jump between different data types (doesn't require additional abstraction layer). – Laszlowaty Apr 16 '19 at 12:19
  • True. It also has the potential to break between different Python versions, and it's not human readable, sooo… – deceze Apr 16 '19 at 12:26
  • How is it not human readable? How is saying "just dump that object into a file" not readable? :) Different python versions shouldn't even be a problem. It's never recommended to just swap between versions. Version migration is a process. – Laszlowaty Apr 16 '19 at 12:29
  • The file that is written is not human readable. The code that writes it is, the resulting file is not. That may or may not be a problem. You also don't know whether this file is supposed to be interchangeable with different systems and/or versions. – Pickling is an entirely cromulent thing to do, no doubt. But you can't universally claim that it's "correct" when it has a number of caveats you need to be aware of. – deceze Apr 16 '19 at 12:49
  • Ok, I have changed `correct` to `a` :) I guess there is no point to continue this discussion. – Laszlowaty Apr 16 '19 at 13:02