6

我有一个接受字符串、列表和字典的函数

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

但它返回一个错误

ValueError:解包的值太多

我的参数是

superDynaParams('Mark Paul',
                'programming','arts','japanese','literature','music',
                father='papa',mother='mama',sister='neechan',brother='niichan')
4

2 回答 2

14

您正在遍历字典:

for key, role in relatives:

但这只会产生keys,因此一次只有一个对象。如果要遍历键和值,请使用以下dict.items()方法:

for key, role in relatives.items():

在 Python 2 上,使用以下dict.iteritems()方法来提高效率:

for key, role in relatives.iteritems():
于 2013-07-24T10:02:36.803 回答
0

您应该使用迭代器来迭代项目:

relatives.iteritems()

for relative in relatives.iteritems():
    //do something
于 2013-07-24T10:04:21.977 回答