Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Answered I ended up going with pickle at the end anyway

Ok so with some advice on another question I asked I was told to use pickle to save a dictionary to a file.

The dictionary that I was trying to save to the file was

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

When pickle saved it to the file... this was the format

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

Can you please give me an alternative way to save the string to the file?

This is the format that I would like it to save in

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

Complete 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") 
like image 677
wakey Avatar asked Feb 04 '11 01:02

wakey


People also ask

What can I use instead of a pickle in Python?

An alternative is cPickle. It is nearly identical to pickle , but written in C, which makes it up to 1000 times faster. For small files, however, you won't notice the difference in speed. Both produce the same data streams, which means that Pickle and cPickle can use the same files.

Can I save a dictionary as a pickle Python?

Use pickle. dump() to save a dictionary to a file Call open(file, mode) with the desired filename as file and "wb" as mode to open the Pickle file for writing in binary. Use pickle. dump(obj, file) with the dictionary as obj and the file object as file to store the dictionary in the file.

Can I save a dictionary in Python?

The pickle module may be used to save dictionaries (or other objects) to a file. The module can serialize and deserialize Python objects. In Python, pickle is a built-in module that implements object serialization.


2 Answers

Sure, save it as CSV:

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

Then reading it would be:

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

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

>>> import json >>> dict = {"hello": "world"} >>> json.dumps(dict) '{"hello": "world"}' 
like image 186
David Wolever Avatar answered Sep 20 '22 18:09

David Wolever


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

>>> 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'} 
like image 43
Glenn Maynard Avatar answered Sep 17 '22 18:09

Glenn Maynard