2015-11-05 69 views
2

我得到這個值誤差值錯誤,要求超過2個值

ValueError: need more than 2 values to unpack) 

,我不知道這意味着什麼。

這裏是我的代碼:

調用 dict.items()鍵和值時
contact_map = {'Dennis Jones': ('989-123-4567', '[email protected]'), 'Susan': ('517-345-1234', '[email protected]'), 'Miller, Matthew': ('616-765-4321', '[email protected]')} 
FORM = "{:<s};{:<d};{:<s}" 

out_file = input("Enter a name for the output file: ") 
output_file= open(out_file, "w") 

for name, phone, email in contact_map.items(): 
    output_file.write(FORM.format(name, phone, email)) 

output_file.close() 

回答

4

必須有兩個存在。之後,您需要解壓縮價值部分以獲取電話和電子郵件。

for name, value in contact_map.items(): 
    phone = value[0] 
    email = value[1] 
    output_file.write(FORM.format(name, phone, email)) 
4

你得到的錯誤,因爲你試圖解壓的len==3name, phone, email)一個元組,但items()回報(key, value),其中value在這種情況下是長度TUP 2.

你可以將其解壓爲一行:

for name, (phone, email) in contact_map.items(): 
2

dict.items()返回一個帶有鍵和值的元組。的dict.items()第一個元素是:

('Dennis Jones', ('989-123-4567', '[email protected]')) 

譯員希望你這個元組解包到兩個值(一個用於'Dennis Jones',其他爲('989-123-4567', '[email protected]'))。爲了循環三個項目(姓名,電話和電子郵件),您可以在括號內圍繞phone, email解開內部元組:

for name, (phone, email) in contact_map.items(): 
    output_file.write(FORM.format(name, phone, email))