2011-08-18 57 views
4

全部,Python字典獲取方法

我在字典上循環並計算出現的值。爲此,我使用另一個字典的賦值語句中的get方法。這將返回語法錯誤「無法分配給函數調用」

counts = {} 
mydict = {'a':[1,2,5], 'b': [1,2,10]} 
for key,value in mydict.iteritems(): 
    counts(value[1]) = counts.get(value[1], 0) + 1 

爲什麼分配會嘗試指向函數而不是返回值?

回答

2
counts = {} 
mydict = {'a':[1,2,5], 'b': [1,2,10]} 
for key,value in mydict.iteritems(): 
    counts[value[1]] = counts.get(value[1], 0) + 1 

您需要括號而不是括號才能從字典中獲取項目。

另外,你這樣做是艱難的。

from collections import defaultdict 

# automatically start each count at zero 
counts = defaultdict(int) 
# we only need the values, not the keys 
for value in mydict.itervalues(): 
    # add one to the count for this item 
    counts[value[1]] += 1 

# only on Python 2.7 or newer 
from collections import Counter 

counts = Counter(value[1] for value in mydict.itervalues()) 
+0

Python的需要塊縮進。你的'for'主體沒有縮進。 – cdhowie

+0

Python需要縮進?我永遠不會知道!這顯然只是一個錯字。 – agf

+0

我是個白癡,我必須在工作當天停止切換語言。另外,感謝您指出defaultdict位,我沒有意識到這一點。 –

1

而不是counts(value[1]) = ...你想要counts[value[1]] = ...

0

更改此:

counts(value[1]) 

這樣:

counts[value[1]] 

代碼如下所示:

counts = {} 
mydict = {'a':[1,2,5], 'b': [1,2,10]} 
for key, value in mydict.iteritems(): 
    counts[value[1]] = counts.get(value[1], 0) + 1 
0
counts[value[1]] = counts.get(value[1], 0) + 1 

應該

counts[value[1]] = counts.get(value[1], 0) + 1