Richard Okpala
Richard Okpala

Reputation: 13

Python Sort Frequency

I just started using python in school and i have a question i have been trying to figure out for a while

The problem is sort a list by frequency and the list also contains strings for ex given function call

SortByFrequency(['pie', 6, 'pie', 9, 6, 7, 9, 9]

it should return

[9, 9, 9, 'pie', 'pie', 6, 6, 7]

How could i find the solution using python thanks My code i already tried was trying to using a dictionary and print the elements somehow

my_Dict ={}
for i in mylist:
       if i not in my_dict:
and count the occurrences 

Upvotes: 1

Views: 83

Answers (3)

Skycc
Skycc

Reputation: 3555

If this is not some sort of school assignment that not allow to use python module, don't reinvent the wheel, it can be done as below using collections module

import collections
def SortByFrequency(lst):
  return list(collections.Counter(lst).elements())

SortByFrequency(['pie', 6, 'pie', 9, 6, 7, 9, 9])
# this return [9, 9, 9, 'pie', 'pie', 6, 6, 7]

My own attempt to solve this with dictionary would be

def SortByFrequency(mylist):
    my_dict = {}
    for i in mylist:
        my_dict[i] = my_dict.get(i,0) + 1
    return sorted(sorted(mylist,key=str), key=my_dict.get, reverse=True)

SortByFrequency(['pie', 6, 'pie', 9, 6, 7, 9, 9])
# but this does not guarantee the order when we have multiple values with same frequency
# this will return [9, 9, 9, 6, 6, 'pie', 'pie', 7]

Upvotes: 1

fl00r
fl00r

Reputation: 83680

You have to create auxiliary dict with counters

list_ = ['pie', 6, 'pie', 9, 6, 7, 9, 9]
dict_ = {}
for i in list_:
  dict_[i] = dict_.get(i, 0) - 1
# Your dict_ now is following:
# {6: -2, 7: -1, 9: -3, 'pie': -2}
sorted(list_, key=dict_.get)
#=> [9, 9, 9, 'pie', 6, 'pie', 6, 7]

Upvotes: 0

trincot
trincot

Reputation: 350290

You were on the way to build the dictionary. Complete it like this:

    if i not in my_dict:
        my_dict[i] = 0 # define this entry
    my_dict[i] += 1 # increment it (number of occurrences of i)

Then you just need to sort it, using the dictionary as key:

def sortByFrequency(mylist):
    my_dict ={}
    for i in mylist:
        if i not in my_dict:
            my_dict[i] = 0
        my_dict[i] += 1
    return sorted(mylist, key=lambda i: -my_dict[i])

The minus sign is a quick way to sort in descending order. Note that it is more common to write the function with an initial lower case letter, as an initial capital is commonly reserved for class names.

Upvotes: 0

Related Questions