Reputation: 11
I know others have asked about this error, but I'm not sure why I keep getting this error for this code. I'm writing a code to open and read a textfile, then replace each letter in it with a new letter. The letters and their replacements are specified in my dictionary "replacements."
This is my code right now:
def decode(text):
replacements={'a':'L','b':'A','c':'O','d':'Z','e':'M','f':'V','g':'R','h':'B','i':'U','j':'S','k':'Q','l':'K','m':'Y','n':'J','o':'W','p':'H','q':'E','r':'X','s':'T','t':'P','u':'F','v':'I','w':'G','x':'C','y':'D','z':'N'}
infile=open(text).read()
outfile=open("output.txt",'w')
for letter in infile:
for old,new in replacements:
newtext=infile.replace(old,new)
outfile.write(newtext)
infile.close()
When I run the code, the error message comes up for the line "for old,new in replacements" and tells me it needs more than 1 value to unpack. I'm very new to programming .. can someone please explain why I'm getting this error?
Upvotes: 1
Views: 573
Reputation: 2510
I think Jakob's answer solved the problem but I would like to rearrange the code a little bit.
def decode(text):
replacements={'a':'L','b':'A','c':'O','d':'Z','e':'M','f':'V','g':'R','h':'B','i':'U','j':'S','k':'Q','l':'K','m':'Y','n':'J','o':'W','p':'H','q':'E','r':'X','s':'T','t':'P','u':'F','v':'I','w':'G','x':'C','y':'D','z':'N'}
with open(text, 'r') as infile:
instr = infile.read()
for old,new in replacements.iteritems():
instr = instr.replace(old, new)
with open("output.txt", 'w') as outfile:
outfile.write(instr)
Doing replacement doesn't require looping through all the letters. It will find convert all matches.
It is easier to use with open
, since it will take care of close
automatically.
Hope these suggestions help you learn Python.
Upvotes: 0
Reputation: 34688
for old,new in replacements:
Will iter the keys in a dict.
for old,new in replacements.iteritems():
Will iterate the key and value in the dict
Upvotes: 5