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

2024/11/20 6:17:57

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 pickletmp = 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", "*" * 12print "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] = codeoutput = 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 = 1while 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 membersprint "\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")
Answer

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"}'
https://en.xdnf.cn/q/26355.html

Related Q&A

python equivalent of functools partial for a class / constructor

I want to create a class that behaves like collections.defaultdict, without having the usage code specify the factory. EG: instead of class Config(collections.defaultdict):passthis:Config = functools.p…

Set the font size in pycharms python console or terminal

There are terminal and python console in pycharm, which are very convenient. But I found that the font size was too small to recognize in terminal or python console. How can change the font size in the…

How to filter model results for multiple values for a many to many field in django

I have the following Model:class Group(models.Model):member = models.ManyToManyField(Player, through=GroupMember)name = models.CharField(max_length=20, unique=True)join_password = models.CharField(max_…

Why is string comparison so fast in python?

I became curious to understand the internals of how string comparison works in python when I was solving the following example algorithm problem:Given two strings, return the length of the longest comm…

What is a namespace object?

import argparseparser = argparse.ArgumentParser(description=sort given numbers) parser.add_argument(-s, nargs = +, type = int) args = parser.parse_args() print(args)On command line when I run the comma…

How to get the element-wise mean of an ndarray

Id like to calculate element-wise average of numpy ndarray.In [56]: a = np.array([10, 20, 30])In [57]: b = np.array([30, 20, 20])In [58]: c = np.array([50, 20, 40])What I want:[30, 20, 30]Is there any …

Spark 1.4 increase maxResultSize memory

I am using Spark 1.4 for my research and struggling with the memory settings. My machine has 16GB of memory so no problem there since the size of my file is only 300MB. Although, when I try to convert …

Java abstract/interface design in Python

I have a number of classes which all share the same methods, only with different implementations. In Java, it would make sense to have each of these classes implement an interface or extend an abstract…

PyCharm - no tests were found?

Ive been getting na error in PyCharm and I cant figure out why Im getting it:No tests were foundThis is what I have for my point_test.py: import unittest import sys import ossys.path.insert(0, os.path.…

Does Python PIL resize maintain the aspect ratio?

Does PIL resize to the exact dimensions I give it no matter what? Or will it try to keep the aspect ratio if I give it something like the Image.ANTIALIAS argument?