2017-07-31 1 views
-1

J'ai un dictionnaire à afficher. Je veux afficher seulement les 15 plus courants. quand l essayer d'afficher tout cela fonctionne cependant lorsque vous essayez de l pour l .most_common() obtenir une erreurnp.arange (len (dictionnary_new.keys())) AttributeError: l'objet 'list' n'a pas d'attribut '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() 

Il fonctionne bien. Cependant je veux montrer 15 la plus commune

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

puis l obtenir l'erreur suivante:

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

qui est impossible avec le code que vous avez posté. Vous avez probablement déjà fait 'dictionnary_new = dictionnary_new.keys()' quelque part, en convertissant en liste (python 2) –

Répondre

1

most_common retourne une liste de tuples, pas un dict; de sorte que dictionary_new est un misnomer. Vous pouvez lancer le type dict en appelant dict sur le résultat:

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

Ou vous pouvez prendre les clés et les valeurs sans faire l'aller-retour de la reconstruction d'un dict avec:

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

Merci cela fonctionne – vincent