-2

Hi would like to store a dictionary in a file but my code doesn't work.

Here the code:

d=open('dict.txt', 'w')
for key, v in dict_ens.iteritems(): # dict_ens is another dict i have
    dict_ens[key]=dict_ens[key][2:]
    if key in enstts: #
       d.write(key, v)
    else : 
       d.write('no key')

d.close()   

what could be wrong with that???

Alice
  • 197
  • 1
  • 1
  • 9
  • http://stackoverflow.com/questions/7100125/storing-python-dictionaries, http://stackoverflow.com/questions/17322273/store-a-dictionary-in-a-file-for-later-retrieval, http://stackoverflow.com/questions/19201290/how-to-save-a-dictionary-to-a-file-in-python, Lots of duplicates of this Question. – Tom Myddeltyn Jun 21 '16 at 21:23

1 Answers1

3

There are several possible ways your code could fail, but without a reproducible example or the error message I can't give you a specific reason.

I would suggest an alternative approach. A simple way to save a dictionary is using the "pickle" library.

To save the dictionary as a pickle file, try this:

import pickle
with open('path_and_filename.pickle', 'wb') as handle:
    pickle.dump(name_of_dict, handle)

You can open a saved dictionary like this:

with open('path_and_filename.pickle', 'r') as handle:
    variable_name = pickle.load(handle)
Nick Becker
  • 4,059
  • 13
  • 19