简体   繁体   中英

ValueError: too many values to unpack (expected 2) errors

My code:

def dictest():
    global my_glossary
    # read all lines of the file
    inFile = open("glossary.txt", "r")
    inText = inFile.read()
    inFile.close()

    my_glossary = {}
    # iterate through all lines, after removing the line-end character(s)
    for line in inText.splitlines():
        if line != '':           # ignore empty lines
            (key,value) = line.split(",")
            my_glossary[key] = value

    addToGlossary = entryNew.get()
    addToGlossaryDef = outputNew.get()

    my_glossary[addToGlossary] = addToGlossaryDef

    # list all the dictionary entries
    for k,v in my_glossary.items():
        print('key:', k, ', value:', v)

My Output:

Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__
return self.func(*args)
File "I:\School\Working Glossary.py", line 59, in MultiFunc
dictest()
File "I:\School\Working Glossary.py", line 14, in dictest
(key,value) = line.split(",")
ValueError: too many values to unpack (expected 2)

I am trying to accomplish making of a keywords glossary using a text file as storage. I keep running into this error which is causing the program to not work.

My text file contents:

bug, this is a test
test, this is another test
testing,testing
123,12354

I think you want this:

>>> line = "hello,world,foo,bar"
>>> (key, value) = line.split(",", 1)
>>> key
'hello'
>>> value
'world,foo,bar'
>>>

The change being: (key, value) = line.split(",", 1)

Passing 1 as the second argument to split tells split to stop after it comes across 1 comma, passing the rest of the line to value.

From the docs ,

str.split([sep[, maxsplit]]) (...) If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM