[Tutor] python equivalent to perl hash slices?

Bill Campbell bill at celestial.net
Tue Aug 3 23:29:26 CEST 2004


Is there a python equivalent to perl's hash slices which I use extensively
to simplify jobs such as parsing tabular data.  As an example, in perl I
might handle a file where the first line of the file is a tab delimited set
of column names, with something like this:

#!/usr/local/bin/perl

my $line1 = <>; # get first line of input
chomp($line1);
my @fields = split("\n", $line);
my @outlist = qw(field1 field2);
my %record;
while(<>) {
	chomp;
	@record{@fields} = split("\n");
	# %record is now a hash (dictionary) with keys in the order
	# specified in the first line.
	print join("\t", @record(@outlist)) . "\n";
	# This prints only the members of the %record dictionary
	# with the keys specified in @outlist
}
__END__

I now use this extensively with mysql and postgresql database functions to
write generic classes based on table metadata, and to do conversions of
data from other sources (e.g. ancient Unify RDBMS SQL output).

Bill
--
INTERNET:  bill at Celestial.COM   Bill Campbell; Celestial Software LLC
UUCP:              camco!bill   PO Box 820; 6641 E. Mercer Way
FAX:           (206) 232-9186   Mercer Island, WA 98040-0820; (206) 236-1676
http://www.celestial.com/

"I do not feel obliged to believe that the same God who has endowed us
with sense, reason, and intellect has intended us to forego their use."
                                -- Galileo Galilei


More information about the Tutor mailing list