Skip to content
Advertisement

Counting dictionary elements from Perl to Python

Looking for a best way to translate this piece of code from Perl to Python:

my @arr = ();
#          [  0  ,  1  ,   2   ,   3  ]
push @arr ,[$time,$host,$status,$bytes];
  my %reqs_host;
  my %bytes_host;
  my %errors_host;
  foreach(@arr){  
    $reqs_host{$_->[1]}++;
    $bytes_host{$_->[1]} += $_->[3];
    $errors_host{$_->[1]}++ if $_->[2] =~ /^[45]/;
  }

If I understand it correctly the cycle above iterates through each element in arr array and how many time host appear, how many bytes count are related to it and errors…

But I don’t quite get the meaning of default variable $_, have Python background, not Perl.

UPDATE: after some brainstorming, I’ve come complete understanding of these Perl code but still not sure how to do it in Python, especially this piece:

$reqs_host{$_->[1]}++;

Advertisement

Answer

Not tested but should be something like this:

arr = []
arr.append((time, host, status, bytes_))
reqs_host, bytes_host, errors_host = {}, {}, {}
for item in arr:
    reqs_host[item[1]] = reqs_host.get(item[1], 0) + 1
    bytes_host[item[1]] = bytes_host.get(item[1], 0) + item[3]
    if item[2] and item[2][0] in "45": 
        errors_host[item[1]] = errors_host.get(item[1], 0) + 1
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement