简体   繁体   中英

ValueError: too many values to unpack in Python Dictionary

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')

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():

You should use an iterator instead to iterate over the items:

relatives.iteritems()

for relative in relatives.iteritems():
    //do something

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM