[Tutor] Need help with dict.calculation
Sean 'Shaleh' Perry
shalehperry@attbi.com
Wed, 23 Jan 2002 22:32:48 -0800 (PST)
On 18-Jan-2002 Eve Kotyk wrote:
> In the script below I would like to add up the totals for each item into
> one final total. So far I haven't come up with anything. Help.
>
I have been writing a program at work which reads a log and keeps a running
count of machine reboots per machine. A nifty way to handle the increment is
the get() method of dictionaries.
dict[key] = dict.get(key, 0) + 1
OK, so this doesn't help directly, but I thought I would share. Onto the real
help.
Another useful python function is 'reduce'. reduce takes a list and runs a
function on each item in the list plus a running variable.
from above I have:
import operator
count = reduce(operator.add, dict.values())
print "Total reboot count for all machines was " + count
What reduce does is more clear if I show you what operator.add looks like:
def add(x, y):
return x + y
so what the reduce function does internally is basically:
value = 0
for item in list:
value = function(value, item)
return value
Hope this gives you some glimpses of python's abilities.