in reply to (jeffa) Re: Converting Python to Perl and back again
in thread Converting Python to Perl and back again

Okay, I've got another fine Python question for you wise Perlmonks (well, know thy enemy, right? ;-). Say I want data such as:

genesis = { "Foxtrot":({"instrumental":"Okay"}, {"vocals":"Good"}), "D +uke":({"vocals":"Better"}) }

How would I go about initially populating the dictionary? Say, as if I was reading from a database and looping over it. There isn't an insert or append operator for dictionaries, and I can't seem to just go: genesis["Foxtrot"]["instrumental"] = "Okay" Any ideas? Thanks.

Replies are listed 'Best First'.
(jeffa) 3Re: Converting Python to Perl and back again
by jeffa (Bishop) on Apr 04, 2003 at 13:48 UTC
    That's right, what you have is illegal syntax in either language. You are trying to access a HoH (hash of hashes) instead of what you really have, a LoH (list of hashes). You simply are missing the array index:
    genesis['Foxtrot'][0]['instrumental'] = 'excellent' $gensis->{Foxtrot}[0]{instrumental} = 'excellent';
    Now then, as for populating these datastructures from a database ... well, i can't help you much with Python. You'll have to read the docs, but i can say that Perl's DBI has methods that will form these datastructures for you, methods such as:
    • selectall_arrayref
    • selectall_hashref
    • fetchrow_arrayref
    • fetchrow_hashref
    and more. I usually only use selectall_arrayref, but sometimes i need the lookup power of hashes. You have to ensure that all of your data has unique id's in order for hashes to work safely (without clobbering existing keys). Recently i decided to roll my own:
    # takes prepared statement handle and returns LoH sub db2tmpl { my ($sth) = @_; $sth->execute; my $fields = $sth->{NAME}; my $rows = $sth->fetchall_arrayref; my @loh; for my $row (@$rows) { my %hash; @hash{@$fields} = @$row; push @loh, {%hash}; } return \@loh; }
    This is very useful with HTML::Template, though i can't help but feel i am re-inventing a wheel. At any rate, i wish you the best of luck. :)

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    

      Thanks for reply. Sorry for the confusion, what I meant by populating the datastructure was the actual looping over and adding entries (this seems pretty straightforward now given your other post). I don't have any problems with reading the data from the database, the docs were decent in both languages for that :).