Reputation:
I have a file that has names put together that are related to each other, and I need the first set to a key, the second to a value, but when I run the program, I get the error
ValueError: too many values to unpack
I have researched this, but, I haven't found a way to fix it. Below is the code, and a link to some of the material I found in trying to fix this issue. http://www.youtube.com/watch?v=p2BwrdjlsW4
dataFile = open("names.dat", 'r')
myDict = {}
for line in dataFile:
k,v = line.strip( ). split(",")
myDict[k.strip (":")] = v.strip ( )
print(k, v)
dataFile.close()
def findFather(myDict, lookUp):
for key, value in myDict.items ( ):
for v in value:
if lookUp in value:
return key
lookUp = raw_input ("Enter a son's name: ")
print "The father you are looking for is ",findFather(myDict, lookUp)
the file is saved as "names.dat" and is listed all on one line with the values:
john:fred, fred:bill, sam:tony, jim:william, william:mark, krager:holdyn, danny:brett, danny:issak, danny:jack, blasen:zade, david:dieter, adam:seth, seth:enos
Upvotes: 0
Views: 224
Reputation: 14360
The code
line.strip( ). split(",")
returns a list like:
["jhon:fred", "fred:bill", "sam:tony", ...]
so, when you do
k,v = line.strip( ). split(",")
you're trying to put all values of that list into k
and v
that are only two.
Try this code:
for line in dataFile:
for pair in line.strip(). split(","):
k,v = pair. split(":")
myDict[k.strip (":")] = v.strip()
print(k, v)
NOTE: The code above is just for remove the error you're getting. I do not guarantee that this code is going to do what you want to do. Also I've not idea about what are you trygin to du with the code:
myDict[k.strip (":")] = v.strip()
Upvotes: 1