hash tables in python?

Greg Jorgensen greg at pdxperts.com
Mon May 21 05:46:07 EDT 2001


On Mon, 21 May 2001 apark at cdf.toronto.edu wrote:

> 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"
> 	}
> ...
> I'm thinking that there has to be a better way to program this...
> Am I wrong?

Python's built-in dictionary type is equivalent to Perl's hash table. For
example, if the file named users.txt has one line per user, containing a
user ID followed by first name and last name, you can create a dictionary
of first and last names keyed by user ID like this:

    f = open('users.txt', 'r')   # open file
    users = {}                   # new empty dictionary

    while 1:
        s = f.readline()         # read next line
        if not s: break          # exit loop when end of file
        userid = s.split(None,1)[0]     # get first token
	username = s.split(None,1)[1:]  # get rest of line
        users[userid] = username # add entry to dictionary

    f.close()

The key and value of a dictionary don't have to be simple strings. From
your sample code it looks like a tuple (basically a list that can't be
changed) of month, date, day, time, and file keyed by username may be what
you want.

I recommend the Python tutorial at python.org.

Greg Jorgensen
PDXperts LLC
Portland, Oregon USA
gregj at pobox.com





More information about the Python-list mailing list