how can I avoid abusing lists?

Jim Segrave jes at nl.demon.net
Sat Jul 8 05:37:26 EDT 2006


In article <1152290319.685783.106250 at s16g2000cws.googlegroups.com>,
Rob Cowie <cowie.rob at gmail.com> wrote:
>Just forget the lists...
>
>counters = {0:0, 1:0, 2:0, 3:0, 4:0}
>
>def increment(value):
>    counters[value] += 1
>
>increment(1)
>increment(1)
>increment(3)
>increment(4)
>
>print counters[0]
>>>> 0
>print counters[1]
>>>> 2
>print coutners[2]
>>>> 0
>print counters[3]
>>>> 1
>print coutners[4]
>>>> 1
>
>The increment function should probably include a try:...except:
>statement to catch KeyErrors that would arise if you passed a value
>that is not a key in the counters dictionary.
>
>Rob C
>

counters = {}
def increment(value):
    counters[value] = counters.get(value, 0) + 1

increment(1)
increment(1)
increment(3)
increment(4)
increment('a string key')


keyz = counters.keys()
keyz.sort()
for k in keyz:
    print k, counters[k]

Takes care of IndexError and ValueError. It does not report keys that
don't get incremented. If that's important, then initalise counters as
in the quoted posting.

For Python 2.4 and later, you can replace the keyz =
counts.keys()/keyz.sourt() for k in keyz: with

for k in sorted(counters.heys()):
   print k, counters[k]


-- 
Jim Segrave           (jes at jes-2.demon.nl)




More information about the Python-list mailing list