Newbie Questions: Swithing from Perl to Python

Roy Smith roy at panix.com
Sun Oct 26 08:29:33 EST 2003


"Luther Barnum" <SpamSucks at rr.com> wrote:
> Actually it could have been written using split. Using regular expressions
> makes it a little more flexible. Python has that so that is not the issue
> really. It's just that I read that you cannot change a dictionary value and
> I wanted to see how it was done in Python. My last question is how do you
> iterate over this to get the values by key.
> 
>  While(<FILE>) {
>      chomp;
>      @line = split;
>          $server = $3;
>          $error = $4;
> 
>          $server_totals{$server}++;
>          $error_totals{$error}++;
>      }

Who said you couldn't chage a dictionary value?  The above code 
translates very nicely into Python:

server_totals = {}
error_totals = {]

for line in file:
   line = line.rstrip()    # see note 1
   words = line.split()
   server = words[2]       # see note 2
   error = words[3]

   server_totals[server] += 1
   error_totals[error] += 1

A couple of notes about the translation:

1) Python's rstrip() isn't an exact replacement for Perl's chomp, but 
it's close enough.  It's not an exact replacement for Perl's chop 
either.  Depending on what you want to do, that might be good or bad :-)

2) Python lists are 0-indexed, so words[0] is like Perl's $1.




More information about the Python-list mailing list