Search code examples
pythondictionarymode

finding the mode and multi mode of a given data set


my goal is to find the mode If you have two or more numbers occurring the same number of times then the mode is all those numbers.

my approach was to put the data into a dictionary and grab the key or key(s) with the max value

#codebelow

data=[3 , 4 , 3 ,4 , 4,3,1,1]

dict= {}
for number in data:
    if number in dict:
        dict[number] +=1
        
    else:
        dict[number] = 1

print(dict.keys() , dict.values() )

#output Below

dict_keys([1, 3, 4]) dict_values([2, 3, 3])

how do i access key(s) with greatest value?


Solution

  • Python's collections Module brings the Counter class, which does exactly this in a single line of code.