Perl & Python: Dictionary, Hash

Advertise Here

, 2005-01, 2011-07-25

Python

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

#-*- coding: utf-8 -*-
# python

# 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 array and hash.

Variable of hash datatype must begin with % in their name.

%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'};

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