Sort dictionaries and submit 20 first

1

I have a dictionary with words and their frequency. Genre:

dic = {walt: 2, disney: 1, ola: 5, ...}

To order the dictionary, I did this:

aux = sorted(dicionario, key=dicionario.get, reverse=True)

And to present the top 20 wanted to do so, but not giving.

while count < 20:
    maior.append(dicionario.keys()[count])
    count +=1
return maior
    
asked by anonymous 17.12.2018 / 01:58

2 answers

4

Walt057, I think I have a solution for your code.

When we are defining a dictionary (which is a data structure key: value), we can use several types of variables, either: str; int; float.

So, I made a dictionary for didactic purposes with some random words:

dictionary = {
    'walt': 2, 'disney': 1, 'ola': 5, 'teste': 12, 'you': 9, 'hasd': 6, 'asd1': 7, '91uas': 8, 'h91k': 9, '9ahsdkj': 10,
    'mais': 1, 'uma': 21, 'tchau': 8, 'mãe': 8, 'você': 6, 'computador': 12, 'mouse': 19, 'celular': 29, 'energetico': 9, 'caneta': 10,
    'vigesimo': 20, 'vigesimo primeiro': 20
}

Note that I put 22 items, if you want to check the size, we can use the len () function:

print(len(dictionary))

This will return the dictionary size.

2. To sort, we can use a simplified code:

dictionary_sorted = sorted(dictionary)

This will cause the dictionary to be sorted alphabetically. We used the key to get a list of dictionary keys, and we used get to get the specific value of a key.

If you want to check the dictionary size, it will not remove or add items and will remain the same size as the primary dictionary.

print(len(dictionary_sorted))

The same will still have all 22 items.

3. Since you want to display the first 20 values of the dictionary (sorted by alphabetical order - note that the result will be an array, since dictionaries are not ordered) slice 'the desired:

to_present = dictionary_sorted[:20]

The ':' is an indicator to show the respective positions we want. In case: 20 (note that you will not have anything before the:, and showing up as far as we want). And in response, it will list the words.

If you want to show in a simplified way, without having to loop, you can use the join () function:

print(', '.join(to_present))

In response we will have all the values of to_present (that we slice the first 20)

91uas, 9ahsdkj, asd1, caneta, celular, computador, disney, energetico, h91k, hasd, mais, mouse, mãe, ola, tchau, teste, uma, vigesimo,vigesimo primeiro, você

I hope I've cooperated with your issue.

    
21.12.2018 / 13:28
2

If you used collections.Counter , as suggested in Dictate dictionary and add python values , I believe you have not bothered to read the documentation. Before using any function it is essential that you read the documentation and understand exactly what it does.

The class Counter has the method most_common which, as the name suggests, returns the most common items of the object.

counter = collections.Counter(palavras)
mais_comuns = counter.most_common(20)
    
17.12.2018 / 02:04