2014-10-18 38 views
1

我有以下詞典,也就是從一個XHR請求,其中所述字典中的鍵是由元組產生的JSON對象:爲什麼我會得到錯誤'exceptions.ValueError:太多值解包'?

{(u'goal', u'corner', u'rightfoot'): 1, (u'goal', u'openplay', u'rightfoot'): 3, (u'miss', 
    u'corner', u'header'): 8, (u'goal', u'corner', u'header'): 1, (u'goal', u'openplay', u'leftfoot'): 2, 
    (u'miss', u'openplay', u'rightfoot'): 30, (u'miss', u'corner', u'rightfoot'): 2, (u'miss', 
    u'crossedfreekick', u'header'): 3, (u'goal', u'penalty', u'rightfoot'): 1, (u'miss', u'fastbreak', 
    u'rightfoot'): 2, (u'miss', u'crossedfreekick', u'rightfoot'): 3, (u'goal', u'openplay', u'header'): 
    1, (u'goal', u'crossedfreekick', u'rightfoot'): 1, (u'miss', u'openplay', u'header'): 2, (u'goal', 
    u'crossedfreekick', u'header'): 1, (u'miss', u'openplay', u'leftfoot'): 22, (u'miss', 
    u'directfreekick', u'rightfoot'): 1, (u'miss', u'crossedfreekick', u'leftfoot'): 1} 

我使用下面的代碼段內的有條件和值字典上面:

goal1 = {"'goal','openplay','leftfoot'", "'goal','openplay','rightfoot'", "'goal','openplay','header'", "'goal','openplay','otherbodypart'"} 
          regex1 = sum(int(value) for key, value in regex if key in goal1) 

然而,這將產生以下錯誤消息:

regex1 = sum(int(value) for key, value in regex if key in goal1) 
    exceptions.ValueError: too many values to unpack 

任何人都可以向我解釋WH這是和/或正確的替代語法?

感謝

+0

是什麼'regex'? – 2014-10-18 22:46:49

回答

2
regex1 = sum(int(value) for key, value in regex.items() if key in goal1) 

您需要使用dict.items其中包含鍵和值,循環在regex快譯通你迭代只是鑰匙,所以你不能解開鍵和值因此錯誤。

的按鍵也是元組,所以你需要將鍵作爲元組存儲在goal1

goal1 = {('goal','openplay','leftfoot'), ('goal','openplay','rightfoot'), ('goal','openplay','header'), ('goal','openplay','otherbodypart')} 


print(regex1) 
6 
+0

工作很好,非常感謝! – gdogg371 2014-10-18 22:48:47

+0

沒有問題,不客氣 – 2014-10-18 22:49:12

相關問題