2013-07-24 48 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 
相關問題