[Tutor] Using dictionary to find the mode of a list

Kent Johnson kent37 at tds.net
Fri Oct 26 12:28:08 CEST 2007

Conor Leister wrote:
> I'm just trying to get the mode of a list.
> Here's the code I have that gathers the data and sorts it.  i just need 
> to be able to get the mode of a using a dictionary and i can't seem to 
> figure out anything. i'm completely lost. this code works fine, i just 
> need to add to it and i'm not great with dictionaries.

OK. The mode is the number that appears the most times, so you need to 
count how many times each number appears. A dict works well for this; 
the dict key is the number and the dict value is the count. Can you 
write a loop through your list that accumulates counts? The next step is 
to find the largest count.


> #gather data
> a=[]
> prompt='Enter numbers, blank line to finish:'
> inVal=raw_input(prompt)
> while inVal:
>     a.append(int(inVal))
>     inVal=raw_input(prompt)
> print 'The values you entered:'
> print a
> #Bubble Sort
> i=0
> while i<len(a):
>     j=1
>     while j<len(a)-i:
>         if a[j-1]>a[j]:
>             temp=a[j]
>             a[j]=a[j-1]
>             a[j-1]=temp
>         j=j+1
>     i=i+1
> print 'Values sorted: ' ,a
> ------------------------------------------------------------------------
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

More information about the Tutor mailing list