I have a function that accepts a string, list and a dictionary
def superDynaParams(myname, *likes, **relatives): # *n is a list and **n is dictionary
print '--------------------------'
print 'my name is ' + myname
print 'I like the following'
for like in likes:
print like
print 'and my family are'
for key, role in relatives:
if parents[role] != None:
print key + ' ' + role
but it returns an error
ValueError: too many values to unpack
my parameters are
superDynaParams('Mark Paul',
'programming','arts','japanese','literature','music',
father='papa',mother='mama',sister='neechan',brother='niichan')
The “valueerror: too many values to unpack (expected 2)” error occurs when you do not unpack all the items in a list. This error is often caused by trying to iterate over the items in a dictionary. To solve this problem, use the items() method to iterate over a dictionary.
The most straightforward way of avoiding this error is to consider how many values you need to unpack and then have the correct number of available variables.
Solution. While unpacking a list into variables, the number of variables you want to unpack must equal the number of items in the list. If you already know the number of elements in the list, then ensure you have an equal number of variables on the left-hand side to hold these elements to solve.
The valueerror: too many values to unpack occurs during a multiple-assignment where you either don't have enough objects to assign to the variables or you have more objects to assign than variables.
You are looping over a dictionary:
for key, role in relatives:
but that only yields keys, so one single object at a time. If you want to loop over keys and values, use the dict.items()
method:
for key, role in relatives.items():
On Python 2, use the dict.iteritems()
method for efficiency:
for key, role in relatives.iteritems():
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With