MathCurvesSurfacesWallpaper GroupsGallerySoftwarePOV-Ray
ProgramingLinuxPerl PythonHTMLCSSJavaScriptPHPJavaEmacsUnicode ♥
Web Hosting by 1&1

Python, Ruby, Perl: Dictionary, Hash

Xah Lee, , …,

Python

In Python, there's a special type of data structure called “dictionary” (aka “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
hh = {"john":3, "mary":4, "jane":5, "vicky":7}
print hh                        # {'jane': 5, 'john': 3, 'mary': 4, 'vicky': 7}

# getting value from a key
print hh["mary"]                # 4

# add a entry
hh["pretty"] = 99
print hh                        # {'jane': 5, 'john': 3, 'mary': 4, 'pretty': 99, 'vicky': 7}

# delete a entry
del hh["vicky"]
print hh                        # {'jane': 5, 'john': 3, 'mary': 4, 'pretty': 99}

# get all keys
print hh.keys()                 # ['jane', 'john', 'mary', 'pretty']

# get all values
print hh.values()               # [5, 3, 4, 99]

# check if a key exists
print hh.has_key("mary")        # True

http://docs.python.org/lib/typesmapping.html

Ruby

In Ruby, hash is just called hash.

#-*- coding: utf-8 -*-
# ruby

# define a keyed list
hh = {:john => 3, :mary => 4, :jane => 5, :vicky => 7}
p hh                   # ⇒ {:john=>3, :mary=>4, :jane=>5, :vicky=>7}

# getting value from a key
p hh[:mary]                # 4

# add a entry
hh[:pretty] = 99
p hh                   # ⇒ {:john=>3, :mary=>4, :jane=>5, :vicky=>7, :pretty=>99}

# delete a entry
hh.delete :vicky
p hh                 # ⇒ {:john=>3, :mary=>4, :jane=>5, :pretty=>99}

# get all keys
p hh.keys()                     # ⇒ [:john, :mary, :jane, :pretty]

# get all values
p hh.values()                   # ⇒ [3, 4, 5, 99]

# check if a key exists
p hh.has_key? :mary            # ⇒ true

p hh.has_value? :jenny       # ⇒ false

In Ruby, :something is a “symbol”. It's similar to lisp's symbol. For practical purposes, you can think of it as a static string. Whenever you need to use a string as a label, you should use symbol instead.

In the above example, you could replace all symbols by string.

In Ruby, “everything” is a object. So, creating a string creates a object, which often means it's slow. So, the “symbol” datatype is a solution for that.

Perl

In Perl, keyed-list is called hash table, or just hash. It is done like this:

# -*- coding: utf-8 -*-
# perl

use Data::Dumper qw(Dumper);    # load the Dumper function for printing array/hash

$Data::Dumper::Indent = 0;      # make it print in compact style

# hash table
%hh = ('john'=>3, 'mary'=> 4, 'jane'=> 5, 'vicky'=>7);

print Dumper \%hh;               # {'jane' => 5,'john' => 3,'vicky' => 7,'mary' => 4}

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.

# -*- coding: utf-8 -*-
# perl

use Data::Dumper qw(Dumper); # for printing list or hash

%hh = ('john' =>3, 'mary' => 4, 'jane' => 5, 'vicky' => 7);
print Dumper \%hh;

# get value from a key
print $hh{'mary'};              # 4

# delete a entry
delete $hh{'vicky'};
print Dumper \%hh;              # { 'jane' => 5, 'john' => 3, 'mary' => 4 }

# get all keys
print Dumper [keys %hh];        # [ 'jane', 'john', 'mary' ]

# get all values (Perl 5.12. released in 2010)
print Dumper [values %hh];      # [ 5, 3, 4]

# check if a key exists
print exists $hh{'mary'};       # returns 1, meaning true.

If you are going to get values of a hash, you use $ in front of the hash variable. ⁖ $b{'mary'}.

The Dumper function's argument needs to be a “reference” to the hash. So, you can use it like this: Dumper(\%b) or Dumper([%b]). (parenthesis is usually optional)

Thanks to 孙翰菲 for a tip.

blog comments powered by Disqus