Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ValueError: too many values to unpack in Python Dictionary [duplicate]

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')
like image 283
Netorica Avatar asked Jul 24 '13 10:07

Netorica


People also ask

How do I fix ValueError too many values to unpack in Python?

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.

How do I stop too many values to unpack?

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.

How do I fix ValueError too many values to unpack expected 2?

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.

What does too many values to unpack mean?

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.


1 Answers

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():
like image 57
Martijn Pieters Avatar answered Nov 07 '22 17:11

Martijn Pieters