Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

python 3.7 - How to fix 'not enough values to unpack (expected 2, got 1)' error

I can't for some reason run the code because it says I need two values when I only need one. How to I get past that?

I have tried to delete the value but all I got was an error.

def read_from_file():
    with open("capital_data.txt") as file:
        for line in file:
            line = line.rstrip('
')
            country, city = line.split("/")
            the_world[country] = city



ValueError: not enough values to unpack (expected 2, got 1)

I don't know what else to put; I don't have any other ideas.

**** Problem Rectified, credits to Gino Mempin

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The error is referring to this line:

country, city = line.split("/")

split("/") returns a list containing the words from the string line, split using the / character. For example, if line is "japan/tokyo", then line.split("/") will return the list

['japan', 'tokyo']

If there is no / character, then the list will just contain 1 element. For example if line is "japan,tokyo", splitting it will just return

['japan,tokyo']

What is happening with country, city = ... is called list unpacking, meaning the 1st element is saved to country and the 2nd element of the list is saved to city. If your list is is ['japan', 'tokyo'], then country will get "japan" and city will get "tokyo". If the number of elements in the right-hand side list does not match the left-hand side variables, you will get a "not enough values to unpack" error.

Now, I cannot see what's in capital_data.txt, but most probably, the line's from your file does not have a / delimiter (ex. "japan, tokyo"). So split-ing the line with / results in just 1 list element ("got 1"), but the left-hand side has 2 variables ("expected 2").

To get past that, you need to match your file reader code with your actual file format, such as maybe using the correct delimiter (replacing /).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...