0

I'm trying to use a for loop to print out each person and their responses but keep getting the error "too many values to unpack" and I'm not sure why. I'm trying to finish exercises in a Python tutorial. This is my code:

question = {'Kim':'Yes',
            'Sarah':'No',
            'Jake':'Maybe'}
for friends, answer in question:
    print("\nFriend:%s" % friends)
    print("Answer:%s" % answer)

And this is the error I'm receiving:

ValueError                                Traceback (most recent call last)
<ipython-input-15-38fd8bb38999> in <module>
      8             'Sarah':'No',
      9             'Jake':'Maybe'}
---> 10 for friends, answer in question:
 11     print("\nFriend:%s" % friends)
 12     print("Answer:%s" % answer)

ValueError: too many values to unpack (expected 2)  

Could someone please explain to me how to accurately retrieve the responses in the list while using a for loop.

Nick
  • 138,499
  • 22
  • 57
  • 95

3 Answers3

0

You need to use the items() method method. This will return a list of tuples with the key, value pair. It should look something like this:

for friend, answer in question.items():
    print(f"\nFriend: {friend}")
    print(f"Answer: {answer")
joshmeranda
  • 3,001
  • 2
  • 10
  • 24
0

Pretty simple -- if you debug you'll see "x in question" returns the keys only. Add .items() to get a tuple (or keys() to get keys explictly, or values() for random sorted values).

for friends, answer in question.items():
    print("Answer:%s" % answer)

Returns

Answer:Yes
Answer:No
Answer:Maybe

If you wanted to debug you should have done this and you'd see it:

for x in question:
   print(x, type(x))

Out:

Kim <class 'str'>
Sarah <class 'str'>
Jake <class 'str'>
Doug F
  • 167
  • 1
  • 6
0

if you want both friend and their response you can use items() of a dictionary it allows you to use dictionary in key->value pair.

question = {'Kim':'Yes',
            'Sarah':'No',
            'Jake':'Maybe'}
for friend,answer in question.items():
    print("Friend :- ",friend)
    print("Answer :- ",answer)
    print("------------------")

Output of the above code :-

Friend :-  Kim
Answer :-  Yes
------------------
Friend :-  Sarah
Answer :-  No
------------------
Friend :-  Jake
Answer :-  Maybe
------------------
Parth B Thakkar
  • 115
  • 2
  • 10