Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Exporting values & keys from dictionary in specified way

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading