Reputation: 11
I have the following part of code. When i give the value 'q' as input to x, I would like to stop the execution of the program.
di={}
while True:
x,y=raw_input('Key, Value: ').split(',')
a=int(x)
di[a]=y
if (x=='q'):
break
else
continue
I get an error message that the input command cannot unpack because i gave only one argument. Any help?
Key, Value: 454,fds
Key, Value: 239,ada
Key, Value: q
Traceback (most recent call last);
File "tmp.py", line 3, in <module>
x,y=raw_input('Key,Value: ').split(',')
ValueError: need more than 1 value to unpack
I cannot write 'q' in both x and y.
Upvotes: 1
Views: 5126
Reputation: 79
Your code snippet breaks, because you do tuple unpacking for which you require 2 values. Even if you could use q,q, your code would break, because you assign x to an int, which for the case of q would throw a ValueError.
Instead of using the tuple assignment you could use a list which you can check beforehand.
while True:
alist =raw_input('Key, Value: ').split(',')
if len(alist) is 1 or alist[0] is 'q':
break
x = int(alist[0])
y = alist[1]
di[x]=y
if you really want to use tuple have a look at this post. Is it possible to assign a default value when unpacking?
Upvotes: 1
Reputation: 55479
You just need to reorganize your logic slightly. Test if the 'q' quit string has been given, and break out of the loop if it has. Otherwise, split the string, and insert the data into the dictionary. It's a good idea to permit both 'q' and 'Q' for the quit signal. And it's also a good idea to strip off stray whitespace from the value you're storing in the dict. You don't need to worry about that for the key since int
will ignore leading & trailing whitespace when converting a string.
Here's a cleaned up version of your code.
di = {}
print 'Enter q to quit'
while True:
s = raw_input('Key, Value: ')
if s.lower() == 'q':
break
x, y = s.split(',')
di[int(x)] = y.strip()
print di
demo
Enter q to quit
Key, Value: 1, a
Key, Value: 2 , b
Key, Value: 3 , c
Key, Value: q
{1: 'a', 2: 'b', 3: 'c'}
Upvotes: 0
Reputation: 81604
If the input string doesn't contain ','
then split(',')
returns a list with a single element, which will cause x, y = []
to return the aforementioned error.
Upvotes: 0