Save dictionary to file (alternative to pickle) in Python?

Answer In the end I ended up going to pickle in the end

Well, therefore, with some tips on another matter, I asked that I was told to use pickle to save the dictionary to a file.

The dictionary that I tried to save to a file was

members = {'Starspy' : 'SHSN4N', 'Test' : 'Test1'} 

When pickle saved it to a file ... it was a format

 (dp0 S'Test' p1 S'Test1' p2 sS'Test2' p3 S'Test2' p4 sS'Starspy' p5 S'SHSN4N' p6 s. 

Can you give me an alternative way to save a string in a file?

This is the format that I would like to save to

members = {'Starspy': 'SHSN4N', 'Test': 'Test1'}

The code:

 import sys import shutil import os import pickle tmp = os.path.isfile("members-tmp.pkl") if tmp == True: os.remove("members-tmp.pkl") shutil.copyfile("members.pkl", "members-tmp.pkl") pkl_file = open('members-tmp.pkl', 'rb') members = pickle.load(pkl_file) pkl_file.close() def show_menu(): os.system("clear") print "\n","*" * 12, "MENU", "*" * 12 print "1. List members" print "2. Add member" print "3. Delete member" print "99. Save" print "0. Abort" print "*" * 28, "\n" return input("Please make a selection: ") def show_members(members): os.system("clear") print "\nNames", " ", "Code" for keys in members.keys(): print keys, " - ", members[keys] def add_member(members): os.system("clear") name = raw_input("Please enter name: ") code = raw_input("Please enter code: ") members[name] = code output = open('members-tmp.pkl', 'wb') pickle.dump(members, output) output.close() return members #with open("foo.txt", "a") as f: # f.write("new line\n") running = 1 while running: selection = show_menu() if selection == 1: show_members(members) print "\n> " ,raw_input("Press enter to continue") elif selection == 2: members == add_member(members) print members print "\n> " ,raw_input("Press enter to continue") elif selection == 99: os.system("clear") shutil.copyfile("members-tmp.pkl", "members.pkl") print "Save Completed" print "\n> " ,raw_input("Press enter to continue") elif selection == 0: os.remove("members-tmp.pkl") sys.exit("Program Aborted") else: os.system("clear") print "That is not a valid option!" print "\n> " ,raw_input("Press enter to continue") 
+44
python dictionary save pickle
Feb 04 2018-11-11T00:
source share
6 answers

Of course, save it as a CSV:

 import csv w = csv.writer(open("output.csv", "w")) for key, val in dict.items(): w.writerow([key, val]) 

Then the reading will be:

 import csv dict = {} for key, val in csv.reader(open("input.csv")): dict[key] = val 

Another alternative could be json ( json for version 2.6+ or install simplejson for version 2.5 and below):

 >>> import json >>> dict = {"hello": "world"} >>> json.dumps(dict) '{"hello": "world"}' 
+58
Feb 04 2018-11-11T00:
source share

The most common serialization format for this is currently JSON, which is universally supported and very clearly represents simple data structures such as dictionaries.

 >>> members = {'Starspy' : 'SHSN4N', 'Test' : 'Test1'} >>> json.dumps(members) '{"Test": "Test1", "Starspy": "SHSN4N"}' >>> json.loads(json.dumps(members)) {u'Test': u'Test1', u'Starspy': u'SHSN4N'} 
+52
Feb 04 '11 at 1:40
source share

The YAML format (via pyyaml) may be a good option for you:

http://en.wikipedia.org/wiki/Yaml

http://pypi.python.org/pypi/PyYAML

+6
Feb 04 2018-11-11T00:
source share

Although, unlike pp.pprint(the_dict) , it will not be so beautiful, it will be launched together, str() , at least, will make the dictionary convenient for simple tasks:

 f.write( str( the_dict ) ) 
+6
Feb 01 '14 at 4:26
source share

You asked

Rather give him a chance. How to specify which file to unload from it? //

In addition to writing to a string, the json module provides dump() , a method that writes to a file:

 >>> a = {'hello': 'world'} >>> import json >>> json.dump(a, file('filename.txt', 'w')) >>> b = json.load(file('filename.txt')) >>> b {u'hello': u'world'} 

There is also a load() method to read.

+3
Nov 06 '15 at 14:29
source share

While I offer pickle , if you want an alternative, you can use klepto .

 >>> init = {'y': 2, 'x': 1, 'z': 3} >>> import klepto >>> cache = klepto.archives.file_archive('memo', init, serialized=False) >>> cache {'y': 2, 'x': 1, 'z': 3} >>> >>> # dump dictionary to the file 'memo.py' >>> cache.dump() >>> >>> # import from 'memo.py' >>> from memo import memo >>> print memo {'y': 2, 'x': 1, 'z': 3} 

With klepto , if you used serialized=True , the dictionary would be written to memo.pkl as a pickled dictionary instead of plain text.

You can get klepto here: https://github.com/uqfoundation/klepto

dill is probably the best pick dill , then pickle itself, since dill can serialize almost anything in python. klepto can also use dill .

You can get the dill here: https://github.com/uqfoundation/dill

0
Jan 26 '14 at 23:28
source share



All Articles