pythonfrequency-table

Output the n most frequent numbers in a frequency table as a list


I made a frequency table to count items from a given list. Example input: list[1, 2, 1, 1, 0, 8, 8]

frequencyTable() returns a dict. of items from the list with their occurence counted. printTable() prints that return. With my example it would be sth. like:

1 : 3
8 : 2
2 : 1
0 : 1

And lastly (and where I'm stuck) the function mostFrequentValues() is supposed to output the n most frequent numbers of the returned frequency table in a list. The return of my example with n = 2 should be [1, 8]. My version returns tuples but I need just a list of the values, without anything else. Since I'm new to Python I did not find any way to filter the rest out yet.

def frequencyTable(list):
    freq_table = {}
    for items in list:
        freq_table[items] = list.count(items) 
    return freq_table
def printTable(freq_table):
    for key, value in freq_table.items():
        print(key, ' : ', value)
def mostFrequentValues(freq_table, n):
    most_frequent = Counter(freq_table).most_common(n)
    return most_frequent

Solution

  • You can do list comprehension to return the first element of the tuples:

    from collections import Counter
    def mostFrequentValues(freq_table, n):
        most_frequent = Counter(freq_table).most_common(n)
        return [i[0] for i in most_frequent]
    

    Output (with n = 2):

    [1, 8]