HomeMathComputingArtsWordsLiteratureMusictwitter facebook webfeed

Keyed List in Python and Perl

Advertise Here For Profit

Xah Lee, 2005-01

Python

In Python, there's a special type of data structure called “dictionary” (also known as “keyed list”, “associative array”). It is a unordered list of pairs, each consists of a key and a value.

# 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')

Perl

In Perl, keyed-list is called hash table, or just hash. 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.

blog comments powered by Disqus