Completely frustrating - I have been googling for a solution for this for a couple of hours now. I have this little bit of code that I wish to read a text file into a Python Dictionary. I used this dictionary format internally within the another piece of code I am writing and had no problems. But trying to import it from an external text file I get a syntax error
It doesn't like : or < > I suspect it is to do with the unicode. I have even removed all the illegal characters but it didn't like that either. I even place a u in front of "word.txt" with no success.
Can someone please explain what is the right syntax for the creation of a string in a text file that can be read into a Python dictionary from and external text file.

This is the code

word_dic = eval(open("word.txt").read())

The text file contains the following

'{}maintitle{}': 'pocket', # {}maintitle{} is the text I wished to be replaced by pocket
'{}stylesheet{}': 'generic',
'{}maintitle{}': 'generic',
'{}stylesheet{}': 'generic',

A big thank you in advance

Recommended Answers

All 3 Replies

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)

# pickle load the dictionary
fin = open("dict1.dat", "r")
after_d = pickle.load(fin)

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 a key 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")

# 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}

What you are trying to eval is not valid python code.

I'm not sure what all the curly braces are for, but your could either use

# wrap content in curly braces to make it valid dict syntax
word_dic = eval('{%s}' % open("word.txt").read())

or adapt your format to something like

'{}maintitle{}': 'pocket', # {}maintitle{} is the text I wished to be replaced by pocket
'{}stylesheet{}': 'generic',
'{}maintitle{}': 'generic',
'{}stylesheet{}': 'generic',

Note though that because of the duplicate keys, your dictionary will have only two entries

>>> word_dic
{'{}maintitle{}': 'generic', '{}stylesheet{}': 'generic'}

Thank you for those who contributed to solving my problem. Without your help I would of still being in a state of frustration. Thanks again for your much appreciated help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.