[Tutor] Counting help

Kent Johnson kent37 at tds.net
Tue Aug 23 22:05:57 CEST 2005


Luis N wrote:
> Ideally, you would put your names into a list or dictionary to make
> working with them easier. If all you're trying to do is count them
> (and your list of names is long), you might consider a dictionary
> which you would use like so:
> 
> #This is just the first thing I considered.
> 
> l = ['a list of names']
> 
> d = {}
> 
> for name in namelist:
>     if d.has_key(name):
>         x = d.get(name)
>         d[name] = x + 1
>     else:
>         d[name] = 1     

dict.get() allows a default argument that will be used if the key doesn't exist, so this can be shortened to
for name in namelist:
  d[name] = d.get(name, 0) + 1

Kent



More information about the Tutor mailing list