2013-07-24 51 views
6

我有一个接受一个字符串,列表和字典ValueError异常:值过多在Python解释解压

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: too many values to unpack

我的参数是

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

的可能重复的[Python的ValueError异常:值过多解压](http://stackoverflow.com/questions/7053551/python-valueerror-too-many-values-to-unpack) –

回答

13

您正在浏览字典:

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 
相关问题