If you have a dictionary in your program and want to save and later reload it as a dictionary object, you have to use module pickle. Here is an example ...
# use module pickle to save/dump and load a dictionary object
# or just about any other intact object
import pickle
# create the test dictionary
before_d = {}
before_d[1]="Name 1"
before_d[2]="Name 2"
before_d[3]="Name 3"
# pickle dump the dictionary
fout = open("dict1.dat", "w")
# default protocol is zero
# -1 gives highest prototcol and smallest data file size
pickle.dump(before_d, fout, protocol=0)
fout.close()
# pickle load the dictionary
fin = open("dict1.dat", "r")
after_d = pickle.load(fin)
fin.close()
print( before_d ) # {1: 'Name 1', 2: 'Name 2', 3: 'Name 3'}
print( after_d ) # {1: 'Name 1', 2: 'Name 2', 3: 'Name 3'}
I you have a text file with each line containing akey value pair, you have to build the dictionary internally like this example shows ...
# creating a dictionary from a text file
# key value pairs occupy a line and are separated by a space
# data for the test file of name bowling_score pairs
text = """\
Frank 180
Larry 215
Heidi 150"""
fname = "Bowling.txt"
# write the test file
fout = open(fname, "w")
fout.write(text)
fout.close()
# read the test file in and convert to a dictionary
bowling_dict = {}
for line in open(fname):
name, score = line.split()
bowling_dict[name] = int(score)
print( bowling_dict ) # {'Frank': 180, 'Larry': 215, 'Heidi': 150} vegaseat
DaniWeb's Hypocrite
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417