To sort a dictionary in Python is very simple since the language has its own method for this that works with both dictionaries, such as lists and tuples.
The syntax is sorted(object, key, reverse)
, where, in your case, Object
is the dictionary itself, key
is the form of organisation and reverse
is a boolean to say whether you want to invert the list or not. It is optional and leaving blank will not invert the answer. The key
is also optional and if not informed will make an alphabetical ordering of your keys.
As your case needs sorting by values we will need to increment with another function: items()
.
So just add the following line in your code and then return this variable further down. The lambda function here works as the sorter and is basically an unnamed function. I won’t explain it here, because it’s not the scope of the question, but if you want to know more about it, here’s a good explanation.
ordenado = sorted(orders.items(), key=lambda x: x[1], reverse=True)
return ordenado
Note that as you want an ordering from the highest to the lowest, I gave the value true
for the variable reverse
. At the end your code is:
texto = '''amar e viver, Amar é sonhar, sonhar é viver, viver é curtir, curtir é amar'''
def converte_texto(texto):
pontuacao = ['.',',',':',';','!','?','"','(', ')']
novo_texto = ''.join(c for c in texto if c not in pontuacao).upper()
lista = novo_texto.split()
return lista
def palavras(texto):
palavras = converte_texto(texto)
contagem = dict()
for palavra in palavras :
contagem[palavra] = contagem.get(palavra, 0) + 1
ordenado = sorted(contagem.items(), key=lambda x: x[1], reverse=True)
return ordenado
print(palavras(texto))