Python字典中值的数量过多导致ValueError错误

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

2
这个回答解决了你的问题吗?['too many values to unpack', 遍历字典. key=>string, value=>list] (//stackoverflow.com/q/5466618/90527) - outis
2个回答

14
你正在遍历一个字典:
for key, role in relatives:

但是这只能得到,因此一次只能获取一个对象。如果您想要循环遍历键和值,请使用dict.items()方法:

for key, role in relatives.items():

在 Python 2 中,为了提高效率,请使用 dict.iteritems() 方法:

for key, role in relatives.iteritems():

0
你应该使用迭代器来遍历这些项:
relatives.iteritems()

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接