Home > OS >  Exporting values & keys from dictionary in specified way
Exporting values & keys from dictionary in specified way

Time:11-21

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

CodePudding user response:

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]

CodePudding user response:

Try:

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


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

f = frequency(requests)
f_sorted = dict(sorted(f.items(), key=lambda k: (k[1], k[0]), reverse=True))

print(f)
print(f_sorted)
print(list(f_sorted))

Prints:

{2: 5, 3: 2, 6: 2, 5: 2, 7: 2, 11: 1, 77: 1}
{2: 5, 7: 2, 6: 2, 5: 2, 3: 2, 77: 1, 11: 1}
[2, 7, 6, 5, 3, 77, 11]
  • Related