2005-01-18
In Python, there's a special type of data structure called keyed list. It is a unordered list of pairs, each consists of a key and a value. A keyed-list is called “dictionary”. (Sometimes also known as associative array, hash.)
# define a keyed list aa = {'john':3, 'mary':4, 'jane':5, 'vicky':7} print 'aa is:', aa # getting value from a key print 'mary is:', aa['mary'] # add a entry aa['pretty'] = 99 print 'added pretty:', aa # delete a entry del aa['vicky'] print 'deleted vicky', aa # get just the keys print 'just keys', aa.keys() # to get just values, use “.values()” # check if a key exists print 'is mary there:', aa.has_key('mary')
Reference: Python Doc↗.
Reference: Python Doc↗.
In Perl, keyed-list is called hash, and it is done like this:
%b = ('john'=>3, 'mary'=> 4, 'jane'=> 5, 'vicky'=>7); use Data::Dumper qw(Dumper); print Dumper \%b;
The line “use Data::Dumper qw(Dumper);” loads the function “Dumper” from the package “Data::Dumper”. The purpose of Dumper is to print hashes.
%b = ('john'=>3, 'mary'=> 4, 'jane'=> 5, 'vicky'=>7); use Data::Dumper qw(Dumper); print Dumper \%b; # getting value from a key print $b{'mary'}; # delete a entry delete $b{'vicky'}; print Dumper \%b; # get just the keys print Dumper [keys %b]; # check if a key exists print exists $b{'mary'};
The syntax of keyed list in Perl is fairly complex. Note that to declare a hash, one starts a variable with %. Now, if you are going to get values of a hash, you use $ in front of the hash variable. e.g. $b{'mary'}.
Also note how Dumper sometimes has a backslash in front of %. That is because, the Dumper() function actually requires a “reference” to the hash. The “reference” concept is one of the major problems in many languages, including C, C++, and Java. We won't go into here.
Reference: perldoc perldata↗.
Reference: perldoc perlref↗.
See also:
Page created: 2005-01. © 2005 by Xah Lee.