Exporting values & keys from dictionary in specified way

Question:

New to Python and hitting a wall with this problem.

Scenario: I have a list with multiple unknown integers. I need to take these, sort them and extract the most frequent occurences. If there are more than one instance of an item, then the higher value should be chosen first.

So far, I have made a dictionary to deal with an example request list but I am unsure how to extract the keys and values as specified above.

def frequency(requests):
    freq = {}
    for x in requests:
        if (x in freq):
            freq[x] += 1
        else:
            freq[x] = 1
    print(freq)   # provides expected result
    

#my attempt to sort dictionary and extract required values  
    sorted_freq = dict(sorted(freq.items(), key=lambda x:x[1], reverse=True))
    print(sorted_freq) #printing the keys at this stage doesn't factor in if the key is bigger/smaller for items with same frequency
    print(sorted_freq.keys())
    return


requests = [2,3,6,5,2,7,2,3,6,5,2,7,11,2,77] #example of request

frequency(requests)


#Output for freq = {2: 5, 3: 2, 6: 2, 5: 2, 7: 2, 11: 1, 77: 1}
#Output for sorted_freq = {2: 5, 3: 2, 6: 2, 5: 2, 7: 2, 11: 1, 77: 1}
#Output for sorted_freq.keys = [2, 3, 6, 5, 7, 11, 77]

So in the above, 3, 6, 5 & 7 all have two occurences, similarly 11 & 77 both one occurence.
The output I am looking for is [2, 7, 6, 5, 3, 77, 11].

I have added in the extra prints above to visualise the problem, will only need the final print in the actual code.

Not sure what the optimal way to approach this is, any help would be appreciated.
Thanks

Asked By: newpythonstudent

||

Answers:

from collections import Counter
from itertools import groupby

requests = [2,3,6,5,2,7,2,3,6,5,2,7,11,2,77]

c = Counter(requests)

freq = list()
for i,g in groupby(c.items(), key=lambda t:t[1]):
    freq.extend(sorted([j for j,k in g],reverse=True))
print(freq)

Try to use built-ins as they are really useful, don’t reinvent the wheel 🙂

Output:

[2, 7, 6, 5, 3, 77, 11]
Answered By: Gábor Fekete
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.