2017-07-31 26 views
-1

l有一個要顯示的字典。我只想顯示15個最常見的。當升嘗試顯示它的工作原理然而一切當升儘量使.most_common()升得到一個錯誤np.arange(len(dictionnary_new.keys()))AttributeError:'list'對象沒有屬性'keys'

 for t in range(z): 
      if text[t] != text2[t]: 
       d = (text[t], text2[t]) 
       dictionnary.append(d) 
       print(dictionnary) 

dictionnary_new = collections.Counter(dictionnary) 

pos = np.arange(len(dictionnary_new.keys())) 
width = 1.0 

ax = plt.axes() 
ax.set_xticks(pos + (width/2)) 
ax.set_xticklabels(dictionnary_new.keys()) 

plt.bar(range(len(dictionnary_new)), dictionnary_new.values(), width, color='g') 

plt.show() 

它運作良好。然而升要顯示的15個最常見的

dictionnary_new = collections.Counter(dictionnary).most_common(15) 

那麼L收到以下錯誤:

pos = np.arange(len(dictionnary_new.keys())) 
AttributeError: 'list' object has no attribute 'keys' 
+1

那是不可能的您發佈的代碼。你可能已經在'dictionnary_new = dictionnary_new.keys()'某處,轉換爲列表(python 2) –

回答

1

most_common返回一個元組的列表,而不是一個字典;所以dictionary_newmisnomer。您可以通過對結果調用字典轉換爲字典類型:

dictionary_new = dict(collections.Counter(dictionnary).most_common(15)) 

或者你可以把鍵和值未做重建字典用的往返:

keys, values = zip(*collections.Counter(dictionnary).most_common(15)) 
+0

謝謝你的工作 – vincent