In article <[EMAIL PROTECTED]>,
Rob Cowie <[EMAIL PROTECTED]> 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           ([EMAIL PROTECTED])

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to