hash tables in python?
Alex Martelli
aleaxit at yahoo.com
Mon May 21 04:24:42 EDT 2001
<apark at cdf.toronto.edu> wrote in message
news:Pine.LNX.4.30.0105202348140.14967-100000 at penguin.cdf.toronto.edu...
> Hi,
>
> I'm trying to translate the following Perl code to Python
>
> [some loop that goes through a file]
> {
> $users1{$username} .= " $month $date $day $time $file\n";
> }
>
> foreach $username (sort keys %users1) {
> $tmp = $users1{$username};
>
> print "$username"
> print "$tmp"
> }
OK, pretty clear (I don't understand why the print statements
at the end aren't just
print $username
&c, i.e., what advantages if any string-interpolation is meant
to give here, but that's OK -- perl isn't meant to be understood:-).
> This is as short as I can present it from the original code. The way
> I have this implemented in Python is that I use two arrays.
> One to keep track of the user name, another one to keep the data in
...
> I'm thinking that there has to be a better way to program this...
> Am I wrong?
No, you're right indeed. Your perl code is easy in Python too, e.g:
users1 = {}
<some loop that goes through a file>:
users1.setdefault(username,[]).append(
" %s %s %s %s %s\n" % (month,date,day,time,file))
usernames = users1.keys()
usernames.sort()
for username in usernames:
print username,
print ''.join(users1[username]),
Alex
More information about the Python-list
mailing list